Popokoko
Popokoko

Reputation: 6543

C#: Create a generic method that can return an enum as List<string>

How can I create a generic method that receives an enum type and return its values and names as a list of strings, so I could loop this list and for each iteration I'll be able to print each of the enum values. For example, consider the next pseudo:

enum MyEnum { A=5, B=6, C=8 }

List<string> createEnumStrings(AnyEnum(??))
{
  List<string> listResult;
  
  // ??
  // a code that will generate:
  // listResult[0] = "Value 5 Name A"
  // listResult[1] = "Value 6 Name B"
  // lsitResult[2] = "Value 8 Name C"

  return listResult;
}

Again, note that this method can get any type of an enum

Upvotes: 3

Views: 2903

Answers (1)

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

public List<string> GetValues(Type enumType)
{
    if(!typeof(Enum).IsAssignableFrom(enumType))
        throw new ArgumentException("enumType should describe enum");

    var names = Enum.GetNames(enumType).Cast<object>();
    var values = Enum.GetValues(enumType).Cast<int>();

    return names.Zip(values, (name, value) => string.Format("Value {0} Name {1}", value, name))
                .ToList();     
}

now if you go with

GetValues(typeof(MyEnum)).ForEach(Console.WriteLine);

will print:

Value 5 Name A
Value 6 Name B
Value 8 Name C

Non-LINQ version:

public List<string> GetValues(Type enumType)
{   
    if(!typeof(Enum).IsAssignableFrom(enumType))
        throw new ArgumentException("enumType should describe enum");

    Array names = Enum.GetNames(enumType);
    Array values = Enum.GetValues(enumType);

    List<string> result = new List<string>(capacity:names.Length);

    for (int i = 0; i < names.Length; i++)
    {
        result.Add(string.Format("Value {0} Name {1}", 
                                (int)values.GetValue(i), names.GetValue(i)));
    }

    return result;
}

Upvotes: 14

Related Questions