Possible Duplicate:
IEnumerable Extension Methods on an Enum
How can I use Generics to create a way of making an IEnumerable from an enum?
Given enums like this:
public enum City
{
London = 1,
Liverpool = 20,
Leeds = 25
}
public enum House
{
OneFloor = 1,
TwoFloors = 2
}
How can I convert these into an IEnumerable lists with two fields named "data" and "value". Would it be possible to have a generic method or way of doing this? Please not that the values are not always sequential.
Despite having similar names enums and enumerables are different things. enum is for defining types, that can have one of predefined values. Look here. IEnumerable is an interface that allows you to enumerate members of any object implementing this interface.
CA1069: Enums should not have duplicate values.
Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.
An enum can be looped through using Enum. GetNames<TEnum>() , Enum. GetNames() , Enum. GetValues<TEnum>() , or Enum.
You can use Enum.GetValues
:
City[] values = (City[])Enum.GetValues(typeof(City));
var valuesWithNames = from value in values
select new { value = (int)value, name = value.ToString() };
How about:
//Tested on LINQPad
void Main()
{
var test = GetDictionary<City>();
Console.WriteLine(test["London"]);
}
public static IDictionary<string, int> GetDictionary<T>()
{
Type type = typeof(T);
if (type.IsEnum)
{
var values = Enum.GetValues(type);
var result = new Dictionary<string, int>();
foreach (var value in values)
{
result.Add(value.ToString(), (int)value);
}
return result;
}
else
{
throw new InvalidOperationException();
}
}
public enum City
{
London = 1,
Liverpool = 20,
Leeds = 25
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With