Convert collections of enums to collection of strings and vice versa
Posted
by Michael Freidgeim
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Michael Freidgeim
Published on Sat, 07 Jul 2012 10:10:11 GMT
Indexed on
2012/07/10
15:17 UTC
Read the original article
Hit count: 207
Filed under:
Recently I needed to convert collections of strings, that represent enum names, to collection of enums, and opposite, to convert collections of enums to collection of
strings. I didn’t find standard LINQ extensions.
However, in our big collection of helper extensions I found what I needed - just with different names:
/// <summary>
/// Safe conversion, ignore any unexpected strings
/// Consider to name as Convert extension
/// </summary>
/// <typeparam name="EnumType"></typeparam>
/// <param name="stringsList"></param>
/// <returns></returns>
public static List<EnumType> StringsListAsEnumList<EnumType>(this List<string> stringsList) where EnumType : struct, IComparable, IConvertible, IFormattable
{
List<EnumType> enumsList = new List<EnumType>();
foreach (string sProvider in stringsList)
{
EnumType provider;
if (EnumHelper.TryParse<EnumType>(sProvider, out provider))
{
enumsList.Add(provider);
}
}
return enumsList;
}
/// <summary>
/// Convert each element of collection to string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objects"></param>
/// <returns></returns>
public static IEnumerable<string> ToStrings<T>(this IEnumerable<T> objects)
{//from http://www.c-sharpcorner.com/Blogs/997/using-linq-to-convert-an-array-from-one-type-to-another.aspx
return objects.Select(en => en.ToString());
}
strings. I didn’t find standard LINQ extensions.
However, in our big collection of helper extensions I found what I needed - just with different names:
/// <summary>
/// Safe conversion, ignore any unexpected strings
/// Consider to name as Convert extension
/// </summary>
/// <typeparam name="EnumType"></typeparam>
/// <param name="stringsList"></param>
/// <returns></returns>
public static List<EnumType> StringsListAsEnumList<EnumType>(this List<string> stringsList) where EnumType : struct, IComparable, IConvertible, IFormattable
{
List<EnumType> enumsList = new List<EnumType>();
foreach (string sProvider in stringsList)
{
EnumType provider;
if (EnumHelper.TryParse<EnumType>(sProvider, out provider))
{
enumsList.Add(provider);
}
}
return enumsList;
}
/// <summary>
/// Convert each element of collection to string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objects"></param>
/// <returns></returns>
public static IEnumerable<string> ToStrings<T>(this IEnumerable<T> objects)
{//from http://www.c-sharpcorner.com/Blogs/997/using-linq-to-convert-an-array-from-one-type-to-another.aspx
return objects.Select(en => en.ToString());
}
© Geeks with Blogs or respective owner