Loop through a C# enum's keys AND values

This question already has an answer here:

  • How do I iterate over an enum? 26 answers

  • Enum类具有您正在寻找的方法。

    foreach(int i in Enum.GetValues(typeof(stuff)))
    {
        String name = Enum.GetName(typeof(stuff), i);
        NewObject thing = new NewObject
        {
            Name = name,
            Number = i
        };
    }
    

    你可以使用LINQ(几乎总是):

    List<NewObject> stuff = Enum.GetValues(typeof(stuffEnum)).Cast<stuffEnum>()
        .Select(s => new NewObject { Name = s.ToString(), Number = (int) s })
        .ToList();
    

    foreach (var enumValue in Enum.GetValues(typeof(StuffEnum)))
    {
        Console.WriteLine("Name: {0}, Value: {1}", enumValue, (int)enumValue);
    }
    

    结果是

    Name: New, Value: 0
    Name: Old, Value: 1
    Name: Fresh, Value: 2
    
    链接地址: http://www.djcxy.com/p/16290.html

    上一篇: 迭代C#中的枚举值

    下一篇: 循环访问C#枚举的键和值