将枚举值转换为字符串数组

Fre*_*wal 14 c# linq enums

public enum VehicleData
{
    Dodge = 15001,
    BMW = 15002,
    Toyota = 15003        
}
Run Code Online (Sandbox Code Playgroud)

我想在字符串数组中得到值15001,15002,15003,如下所示:

string[] arr = { "15001", "15002", "15003" };
Run Code Online (Sandbox Code Playgroud)

我试过下面的命令,但这给了我一些名字而不是值.

string[] aaa = (string[]) Enum.GetNames(typeof(VehicleData));
Run Code Online (Sandbox Code Playgroud)

我也尝试过,string[] aaa = (string[]) Enum.GetValues(typeof(VehicleData));但也没有用.

有什么建议?

Jam*_*mes 22

使用GetValues

Enum.GetValues(typeof(VehicleData))
    .Cast<int>()
    .Select(x => x.ToString())
    .ToArray();
Run Code Online (Sandbox Code Playgroud)

现场演示


小智 17

那么Enum.GetNames呢?

string[] cars = System.Enum.GetNames( typeof( VehicleData ) );
Run Code Online (Sandbox Code Playgroud)

试试看 ;)

  • `System.Enum.GetNames` 将给出名称而不是所要求的 OP 值。 (4认同)
  • `Enum.GetNames` 返回字符串数组而不是单个字符串 (2认同)

Mat*_*and 7

Enum.GetValues会给你一个包含你所有定义值的数组Enum.要将它们转换为数字字符串,您需要转换为int然后转换ToString()它们

就像是:

var vals = Enum.GetValues(typeof(VehicleData))
    .Cast<int>()
    .Select(x => x.ToString())
    .ToArray();
Run Code Online (Sandbox Code Playgroud)

演示