Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq List contains specific values

Tags:

linq

I need to know if the List I am working with contains only some specific values.

var list = new List<string> { "First", "Second", "Third" };

If I want to know if the List contain at least one item with the value "First" I use the Any keyword:

var result = list.Any(l => l == "First");

But how I can write a Linq expression that will return true/false only if the List contains "First" and "Second" values?

like image 723
Raffaeu Avatar asked Dec 29 '22 03:12

Raffaeu


2 Answers

I'm not entirely sure what you want, but if you want to ensure that "First" and "Second" are represented once, you can do:

var result = list.Where(l => l == "First" || l =="Second")
                 .Distinct()
                 .Count() == 2;

or:

var result = list.Contains("First") && list.Contains("Second");

If you've got a longer "whitelist", you could do:

var result = !whiteList.Except(list).Any();

On the other hand, if you want to ensure that all items in the list are from the white-list and that each item in the white-list is represented at least once, I would do:

var set = new HashSet(list); set.SymmetricExceptWith(whiteList); var result = !set.Any();

EDIT: Actually, Jon Skeet's SetEquals is a much better way of expressing the last bit.

like image 154
Ani Avatar answered Jan 21 '23 11:01

Ani


Your question is unclear.

From the first sentence, I'd expect this to be what you're after:

var onlyValidValues = !list.Except(validValues).Any();

In other words: after you've stripped out the valid values, the list should be empty.

From the final sentence, I'd expect this:

var validSet = new HashSet<string>(requiredValues);
var allAndOnlyValidValues = validSet.SetEquals(candidateSequence);

Note that this will still be valid if your candidate sequence contains the same values multiple times.

If you could clarify exactly what your success criteria are, it would be easier to answer the question precisely.

like image 28
Jon Skeet Avatar answered Jan 21 '23 11:01

Jon Skeet