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.