6

I have

List<string> selectedOptions;
Dictionary<string,string> masterList;

masterList comprises of Keys, which are the superset for the values in selectedoptions. Now, I would like to extract all the Values for the intersecting Keys between selectedOptions and masterList.

How would the LINQ query be framed?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
GilliVilla
  • 4,998
  • 11
  • 55
  • 96

1 Answers1

12
IEnumerable<KeyValuePair<string,string>> results = 
    dic.Join(keys, d => d.Key, x => x, (a, b) => a);

or of course

var results2 = keys.Select(k => new {key = k, value = dic[k]});

but this will bomb if keys don't exist.

you could fix this with a Where(k => dic.ContainsKey(k)) clause:

var results3 = keys
     .Where(k => dic.ContainsKey(k))
     .Select(k => new {key = k, value = dic[k]});

After trawling the Linq source, I think that the last method is probably most efficient. Doing a join forces linq to make a Lookup (effectively a multi-entry hashtable) over one of the collections involved in the join. Seeing as we already have a Dictionary which offers the same lookup performance as a Lookup, building a Lookup is superfluous.

spender
  • 117,338
  • 33
  • 229
  • 351
  • this does not serve my purpose. I need filtered values from the dictionary for the matching keys. This is still returning matching keys. not sure if am I doing anything wrong in interpreting the code... – GilliVilla Aug 24 '12 at 18:58
  • @GilliVilla - results3 returns a list with both keys and values, what exactly is the problem? – Hogan Aug 24 '12 at 19:28