簡體   English   中英

從字符串列表中獲取匹配的enum int值

[英]Get matching enum int values from list of strings

我有一個具有不同int值的顏色枚舉

enum Colors { Red = 1, Blue = 2, Green = 5, Yellow = 7, Pink = 10, Black = 15 };

我有一個包含顏色名稱的字符串列表(我可以假設列表中的所有名稱都存在於枚舉中)。

我需要在字符串列表中創建所有顏色的整數列表。 例如 - 對於列表{“藍色”,“紅色”,“黃色”}我想創建一個列表 - {2,1,7}。 我不在乎訂單。

我的代碼是下面的代碼。 我使用字典和foreach循環。 我可以用linq做這件事,讓我的代碼更短更簡單嗎?

public enum Colors { Red = 1, Blue = 2, Green = 5, Yellow = 7, Pink = 10, Black = 15 };

public List<int> getColorInts(List<string> myColors)
{
    // myColors contains strings like "Red", "Blue"..

    List<int> colorInts = new List<int>();
    foreach (string color in myColors)
    {
         Colors result;
         bool success = Enum.TryParse(color , out result);
         if (success)
         {
             colorInts .Add((int)result);
         }
    }
    return colorInts;
}
var res = colorList.Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();

您可以使用Enum.Parse(Type,String,Boolean)方法。 但如果沒有在Enum中找到該值它將拋出異常 在這種情況下,您可以首先使用IsDefined方法過濾數組。

 var res = colorList.Where(x=> Enum.IsDefined(typeof(Colors), x))
                    .Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();

只需將每個字符串投影到適當的枚舉值(當然,確保字符串是有效的枚舉名稱):

myColors.Select(s => (int)Enum.Parse(typeof(Colors), s, ignoreCase:true))

結果:

2, 1, 7

如果可能有不是枚舉成員名稱的字符串,那么您應該使用您的方法與字典或使用Enum.TryParse來檢查名稱是否有效:

public IEnumerable<int> GetColorsValues(IEnumerable<string> colors)
{
    Colors value;
    foreach (string color in colors)
        if (Enum.TryParse<Colors>(color, true, out value))
            yield return (int)value;
}

使用Enum.Parse並將其Enum.Parse為int。

public List<int> GetColorInts(IEnumerable<string> myColors)
{
    return myColors
        .Select(x => Enum.Parse(typeof(Colors), x, true))
        .Cast<int>()
        .ToList();
}

我已經使用Enum.Parse第三個參數為true來使解析案例不敏感。 你可以通過傳遞false或完全忽略參數來區分大小寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM