Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if value exists for a key 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 doesn't have value property, instead of looping over, is there a smarter way to get the result in few lines. the above code is not right, hoping something similar if its possible. I am new to Linq so learning better ways

like image 764
user2271512 Avatar asked Apr 11 '13 19:04

user2271512


1 Answers

The object returned from of the ILookup<TKey, TElement>.Item property (which is what's called when you do someList[...]) is an IEnumerable<TElement>. So you can compare each item directly to your test value. Like this:

var status = someList["Football"].Any(y => y == "Venus Williams");
like image 153
p.s.w.g Avatar answered Nov 14 '22 21:11

p.s.w.g