[英]Return String list from a type instead Enum list in C# Asp Net Core
我有一個類型 Camp,它返回一個字符串列表,下面的代碼使用枚舉進行驗證,我需要讓它返回一個字符串列表,在這種情況下我不能使用枚舉。
我該怎么做?
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);
}
由於Enum.GetNames(typeof(Camp));
返回一個字符串數組,只需轉到ToList
。
public IList<string> getChampionships()
{
return Enum.GetNames(typeof(Camp)).ToList();
}
如果您正在嘗試創建某種類型的地圖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.