C# 将枚举转换为列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17123548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:39:32  来源:igfitidea点击:

Convert Enum to List

c#listenumstype-conversion

提问by Amit

Say i have the following Enum Values

假设我有以下枚举值

enum Language
    {
       CSharp= 0,
        Java = 1,
        VB = 2

    }

I would like to convert them to list of values (i.e) { CSharp,Java,VB}.

我想将它们转换为值列表(即) { CSharp,Java,VB}.

How to convert them to a list of values?

如何将它们转换为值列表?

采纳答案by It'sNotALie.

Language[] result = (Language[])Enum.GetValues(typeof(Language))

will get you your values, if you want a list of the enums.

如果您想要枚举列表,它将为您提供您的价值。

If you want a list of the names, use this:

如果您想要名称列表,请使用以下命令:

string[] names = Enum.GetNames(typeof(Languages));

回答by Amit

If I understand your requirement correctly , you are looking for something like this

如果我正确理解您的要求,您正在寻找这样的东西

var enumList = Enum.GetValues(typeof(Language)).OfType<Language>().ToList();

回答by Shyam sundar shah

You can use this code

您可以使用此代码

  static void Main(string[] args)
  {
   enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

    Array arr = Enum.GetValues(typeof(Days));
    List<string> lstDays = new List<string>(arr.Length);
    for (int i = 0; i < arr.Length; i++)
    {
        lstDays.Add(arr.GetValue(i).ToString());
    }
  }

回答by monrow

If you want to store your enum elements in the list as Language type:

如果要将列表中的枚举元素存储为 Language 类型:

Enum.GetValues(typeof(Language)).Cast<Language>().ToList();

In case you want to store them as string:

如果您想将它们存储为字符串:

Enum.GetValues(typeof(Language)).Cast<Language>().Select(x => x.ToString()).ToList();