简体   繁体   English

从类型返回字符串列表而不是 C# Asp Net Core 中的枚举列表

[英]Return String list from a type instead Enum list in C# Asp Net Core

I have a type Camp that returns a string list and the bellow code validates using enum, I need to make this returns a list of strings and I can't use enum in this case.我有一个类型 Camp,它返回一个字符串列表,下面的代码使用枚举进行验证,我需要让它返回一个字符串列表,在这种情况下我不能使用枚举。

How do I do it?我该怎么做?

public string getChampionships()
{
    string[] enumNames = Enum.GetNames(typeof(Camp)); 
    Dictionary<string, int> dic = new Dictionary<string, int>();
    Array.ForEach(enumNames, val => dic[val] = (int)Enum.Parse(typeof(Camp), val));
    return JsonConvert.SerializeObject(dic);
}

Since Enum.GetNames(typeof(Camp));由于Enum.GetNames(typeof(Camp)); returns an array of strings, just go ToList .返回一个字符串数组,只需转到ToList

public IList<string> getChampionships()
{
     return Enum.GetNames(typeof(Camp)).ToList(); 
}

if your are trying to create some type of map IDictionary<string,int> then your method would look something like this.如果您正在尝试创建某种类型的地图IDictionary<string,int>那么您的方法将如下所示。

public IDictionary<string,int> getChampionships()
{
     return Enum.GetNames(typeof(Camp))
                .ToDictionary(item => item, item => (int)Enum.Parse(typeof(Camp), item)); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM