Raffaeu
Raffaeu

Reputation: 6973

Linq List contains specific values

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?

Upvotes: 4

Views: 10200

Answers (3)

Ani
Ani

Reputation: 113402

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.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 4

cjk
cjk

Reputation: 46415

You can use Intersect to find matches:

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

var test = list.Intersect(comparelist).Distinct().Count() == comparelist.Count();

Upvotes: 2

Related Questions