Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an IEnumerable from an enum [duplicate]

Tags:

c#

.net

enums

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.

like image 720
Samantha J T Star Avatar asked Sep 16 '12 14:09

Samantha J T Star


People also ask

Is an enum an IEnumerable?

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.

Can enum have duplicate values C#?

CA1069: Enums should not have duplicate values.

Can enum inherit from another enum C#?

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.

Can you loop through an enum?

An enum can be looped through using Enum. GetNames<TEnum>() , Enum. GetNames() , Enum. GetValues<TEnum>() , or Enum.


2 Answers

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() };
like image 144
driis Avatar answered Sep 23 '22 14:09

driis


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
}
like image 38
Theraot Avatar answered Sep 23 '22 14:09

Theraot