开发者

Simple question: filter dictionary of a list

imagine I have a list

List<String> B

and a dict开发者_StackOverflowionary

Dictionary<String, int> A

How can I return a Dictionary<String, int> that filtered from A with the keys in B by using Linq?


Easy, using Where to filter the key/value pairs, and then ToDictionary to build a new dictionary.

var c = A.Where(pair => B.Contains(pair.Key))
         .ToDictionary(pair => pair.Key, pair => pair.Value);

If you have a lot of entries, you may want to create a HashSet<string> first:

var strings = new HashSet<string>(B);
var c = A.Where(pair => strings.Contains(pair.Key))
         .ToDictionary(pair => pair.Key, pair => pair.Value);

That will make it faster to test each key.


Out of my head, because I'm on the wrong computer and cannot test. But you should get the idea:

A.Where(val => B.Contains(val.Key)).ToDictionary(val => val.Key, val => val.Value);


If the dictionary is big, you might want to enumerate the B instead of A.

var filtered = B
        .Where(key => A.ContainsKey(key))
        .ToDictionary(key => key, key => A[key]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜