C# 或表达式串联的Lambda实现
C# 或表达式串联的Lambda实现,c#,lambda,C#,Lambda,我不熟悉lambda表达式;我在实践中学习。我有一个关于如何将for循环转换为lambda表达式的问题 EnumHelper.GetEnumFromString是一个助手方法,它获取字符串描述并发回枚举 [Flags] public enum Colors { [DescriptionAttribute("YL")] Yellow = 1, [DescriptionAttribute("RD")] Red = 2
我不熟悉lambda表达式;我在实践中学习。我有一个关于如何将for循环转换为lambda表达式的问题
EnumHelper.GetEnumFromString
是一个助手方法,它获取字符串描述并发回枚举
[Flags]
public enum Colors
{
[DescriptionAttribute("YL")]
Yellow = 1,
[DescriptionAttribute("RD")]
Red = 2,
[DescriptionAttribute("GR")]
Green = 4
}
string colorStr = "GR,RD";
List<Colors> clrs = colorStr.Split(new char[] { ',' }).Select(p => EnumHelper.GetEnumFromString<Colors>(p)).ToList();
Colors currentValidColors = Colors.Green;
for (int i = 0; i < clrs .Count; i++)
{
if (i == 0)
currentValidColors = clrs [i];
else
currentValidColors = currentValidColors | clrs [i];
}
[旗帜]
公共枚举颜色
{
[描述属性(“YL”)]
黄色=1,
[描述属性(“RD”)]
红色=2,
[描述属性(“GR”)]
绿色=4
}
字符串colorStr=“GR,RD”;
List clrs=colorStr.Split(new char[]{',}).Select(p=>EnumHelper.GetEnumFromString(p)).ToList();
颜色currentValidColors=颜色。绿色;
对于(int i=0;i
这就是你的想法吗?ForEach扩展方法仅适用于泛型列表
Colors currentValidColors = 0;
colorStr.Split(new char[] { ',' })
.Select(p => EnumHelper.GetEnumFromString<Colors>(p))
.ToList()
.ForEach(c => currentValidColors |= c);
Colors当前有效颜色=0;
colorStr.Split(新字符[]{',})
.Select(p=>EnumHelper.GetEnumFromString(p))
托利斯先生()
.ForEach(c=>currentValidColor |=c);
这种方式可能更简洁:
Colors currentValidColors =
colorStr.Split(',')
.Select(EnumHelper.GetEnumFromString<Colors>)
.Aggregate((a, b) => a | b);
Colors当前有效颜色=
colorStr.Split(',')
.Select(EnumHelper.GetEnumFromString)
.骨料((a,b)=>a | b);
如果我理解正确,您是在要求linq解决方案(lambda表达式只是创建匿名函数的方法),我不确定是否理解您的问题。您是否对当前代码有问题,或者希望使用不同的当前代码实现?要将字符串描述转换为枚举,可以使用Enum.Parse()或Enum.TryParse()。您需要查看aggregate
扩展方法,将所有颜色
聚合为单个颜色。顺便说一句,颜色实际上代表一种颜色,所以你应该相应地重命名它。是的,这就是我要找的。。。但我听说ForEach不会归还任何东西。是吗?是的,它不返回任何内容。这是我的错别字对不起。现在修好了。currentValidColors的值在|=c语句中设置。