Question

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.

public enum myEnum {
    True,
    False,
    NA
}

I have two lists List1 and List2 and both contain 10 elements. 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. I am trying to avoid writinig long code.

Was it helpful?

Solution

Start out writing the method that can perform the And operation that you want on just two values, using the logic that you described. 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.

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:

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

OTHER TIPS

A bool? (Nullable<bool>) has three values and gives you all of the values you expect if you use the logical and (&) operator:

(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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top