Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query for finding one item in list AND verifying list does not contain another item

Tags:

c#

linq

So far I have come up with this:

list.Any(s => s.EnumIdValue == Close) && !list.Any(s => s.EnumIdValue == Reset || s.EnumIdValue == Cancel);

EnumIdValue contains several different possible values like Close, Reset, Cancel, SomeOtherState, etc. There should never be duplicates but it's still possible.

This does exactly what I want. But would there be a better (shorter) way to write this query?

like image 637
Andrew Avatar asked Feb 08 '23 14:02

Andrew


1 Answers

Your original is fine. The other variant that would work is this:

var newQuery =
    list.Any(s => s.EnumIdValue == EnumIdValue.Close) &&
    list.All(s => s.EnumIdValue != EnumIdValue.Reset &&
                  s.EnumIdValue != EnumIdValue.Cancel);

In English: does the list have at least one Close and is every item in the list not Reset and not Cancel?

By the way, sometimes formatting your code nicely makes a big difference in terms of readability.

like image 176
devuxer Avatar answered Feb 16 '23 02:02

devuxer