c# – 从字符串列表中获取匹配的enum int值
发布时间:2020-12-16 00:24:58 所属栏目:百科 来源:网络整理
导读:我有一个具有不同int值的颜色枚举 enum Colors { Red = 1,Blue = 2,Green = 5,Yellow = 7,Pink = 10,Black = 15 }; 我有一个包含颜色名称的字符串列表(我可以假设列表中的所有名称都存在于枚举中). 我需要在字符串列表中创建所有颜色的整数列表. 例如 – 对
我有一个具有不同int值的颜色枚举
enum Colors { Red = 1,Blue = 2,Green = 5,Yellow = 7,Pink = 10,Black = 15 }; 我有一个包含颜色名称的字符串列表(我可以假设列表中的所有名称都存在于枚举中). 我需要在字符串列表中创建所有颜色的整数列表. 我的代码是下面的代码.我使用字典和foreach循环.我可以用linq做这件事,让我的代码更短更简单吗? public enum Colors { Red = 1,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中找到该值,它将抛出异常. var res = colorList.Where(x=> Enum.IsDefined(typeof(Colors),x)) .Select(x => (int)Enum.Parse(typeof(Colors),true)).ToList(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读