Thursday, January 8, 2009

Converting an enum to a list

Needed to interate through an enum, so I had to convert it to a list. Used generics so that the code could be reused:


public List<keyvaluepair<k,>> BuildListFromEnum<k,>(Type type)
{
var list = new List<keyvaluepair<k,>>();
foreach (K key in Enum.GetValues(type))
{
V name = (V)Convert.ChangeType(Enum.GetName(type, key), typeof(V));
list.Add(new KeyValuePair((K)key, name));
}

return list;
}


This can be used like this:

var statuses = from status in statusList select new NameValue(status.Value, status.Key);

where NameValue looks like this:

[Serializable]
public class NameValue
{
public N Name { get; set; }
public V Value { get; set; }
public NameValue() { }
public NameValue(N name, V value)
{
Name = name;
Value = value;
}
}

No comments: