简体   繁体   English

和枚举列表之间的操作

[英]And Operation between lists of Enums

I have two lists of Enums and I want to perform And kind of operation between them. 我有两个枚举列表,我想在它们之间执行和一种操作。 Let suppose my enum definition has 3 elements true, false and NA. 假设我的枚举定义包含3个元素:true,false和NA。

public enum myEnum {
    True,
    False,
    NA
}

I have two lists List1 and List2 and both contain 10 elements. 我有两个列表List1和List2,都包含10个元素。 I want these results: 我想要这些结果:

True && False = False
True && NA = NA
False && NA = False
True && True = True
False && False = False
NA && NA =  NA 

I want to know to that is there any built-in functionality in C# which can give me results which I mentioned above. 我想知道C#中有任何内置功能可以给我上面提到的结果。 I am trying to avoid writinig long code. 我试图避免写长代码。

Start out writing the method that can perform the And operation that you want on just two values, using the logic that you described. 开始使用您描述的逻辑编写可以对两个值执行所需的And操作的方法。 This is actually handled quite easily, as if either value is False you return False , if none is False and one is NA you return NA , and if both are true you return true, the only remaining case. 这实际上很容易处理,就好像其中一个值为False都返回False ,如果都不为False且一个值为NA返回NA ,如果两个都为true则返回true,这是唯一的情况。

public static myEnum And(this myEnum first, myEnum second)
{
    if (first == myEnum.False || second == myEnum.False)
        return myEnum.False;
    if (first == myEnum.NA || second == myEnum.NA)
        return myEnum.NA;
    return myEnum.True;
}

Next, it appears that you want to compare the item from each list that is at the same index, so the first is compared to the first, the second to the second, etc., to create a new list of the same size as the other two. 接下来,您似乎要比较索引相同的每个列表中的项目,因此将第一个与第一个进行比较,将第二个与第二个进行比较,以此类推,以创建一个与列表大小相同的新列表。另外两个。 You can use Zip , to perform this logical operation using the method we've already defined: 您可以使用Zip ,使用我们已经定义的方法执行此逻辑操作:

var query = list1.Zip(list2, (a,b) => a.And(b));

A bool? bool? ( Nullable<bool> ) has three values and gives you all of the values you expect if you use the logical and ( & ) operator: Nullable<bool> )具有三个值,并为您提供您期望使用逻辑和( & )运算符的所有值:

(bool?)true  & (bool?)false = false
(bool?)true  & (bool?)null  = null
(bool?)false & (bool?)null  = false
(bool?)true  & (bool?)true  = true
(bool?)false & (bool?)false = false
(bool?)null  & (bool?)null  = null

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

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