LINQ querying a Dictionary against a List

丶灬走出姿态 提交于 2020-01-03 11:01:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12114227/linq-querying-a-dictionary-against-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!