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());
}