【问题标题】:How can I create an IEnumerable from an enum [duplicate]如何从枚举创建 IEnumerable [重复]
【发布时间】:2012-09-16 14:00:11
【问题描述】:

可能重复:
IEnumerable Extension Methods on an Enum
How can I use Generics to create a way of making an IEnumerable from an enum?

给定这样的枚举:

public enum City
{
    London    = 1,
    Liverpool  = 20,
    Leeds       = 25
}

public enum House
{
    OneFloor    = 1,
    TwoFloors = 2
}

如何将这些转换为 IEnumerable 列表,其中包含名为“数据”和“值”的两个字段。是否有可能有一个通用的方法或方法来做到这一点?请注意,这些值并不总是连续的。

【问题讨论】:

  • 你想要一个元组的 IEnumerable、一个 IDictionary 还是什么?
  • 我认为它需要是一个 IDictionary,因为我需要字段名称。非常感谢您能给我的任何建议。
  • 检查 driis 对 IEnumerable of Anonymous Types 的回答(它们也可能是元组),检查我的是否有点老派(没有 Linq)IDictionary。

标签: c# .net enums


【解决方案1】:

你可以使用Enum.GetValues:

City[] values = (City[])Enum.GetValues(typeof(City));
var valuesWithNames = from value in values
                      select new { value = (int)value, name = value.ToString() };

【讨论】:

  • 谢谢,我确实看到了 GetValues,但我不确定如何获取这些并将它们放入具有字段名称的集合中?
  • 请查看更新后的答案,其中我使用匿名类型将整数值及其名称选择到 IEnumerable 中。从那里,将它们放入您需要的数据结构中。
  • 我现在就试试这个。我认为这是我需要的。
【解决方案2】:

怎么样:

//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
}

【讨论】:

    【解决方案3】:

    你可以试试这个:

    var cities Enum.GetValues(typeof(City)).OfType<City>()
                   .Select(x =>
                        new
                        {
                             Value =  (int)x,
                             Text = x.ToString()
                        });
    

    编辑

    使用强制转换而不是 OfType

    var cities = ((IEnumerable<City>)Enum.GetValues(typeof(City)))
                                         .Select(x => 
                                             new 
                                             {
                                                 Value =  (int)x,
                                                 Text = x.ToString()
                                             });
    

    【讨论】:

    • 可能是Cast 而不是OfType
    猜你喜欢
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多