Best way to check if key value exists in ILookup <string, string> using linq

ILookup<string, string> someList; Cricket Sachin Dravid Dhoni Football Beckham Ronaldo Maradona 
 bool status = someList.Where(x => x.Key == "Football").Where( y => y.Value == "Ronaldo") 

should return true

 bool status = someList.Where(x => x.Key == "Football").Where( y => y.Value == "Venus williams") 

should return false

ILookup does not have a value property, instead of looping through a loop, there is a smarter way to get the result in multiple lines. the above code is wrong, hoping for something like this if possible. I am new to Linq, so I’m learning the best ways.

+6
source share
4 answers

The object returned from the ILookup<TKey, TElement>.Item (this is what someList[...] called when someList[...] is executed) is IEnumerable<TElement> . This way you can compare each element directly with your test value. Like this:

 var status = someList["Football"].Any(y => y == "Venus Williams"); 
+7
source
 bool status = someList.Where(x => x.Key == "Football").Any( y => y.Value == "Venus williams") 
+2
source

What about:

 var status = someList.Any(grp => grp.Key.Equals("Football") && grp.Contains("Venus Williams")); 

Explanation: ILookup is IEnumerable from IGrouping — the grouping has the Key property and is a list of string values

+1
source

I would use .Any(x => x.Value == "value") .

You may be mistaken, but I think you will want to do this in 2 steps, but make sure that the first (key) search succeeds before continuing to evaluate the search to make sure that you are not executing .Any() on a null object

0
source

All Articles