Reputation: 429
I have a dictionary D1 like this
and a list L1 like this
I want to have a dictionary like this (Filtering those key-value pairs whose key is present in the list )
So, I tried D1.Where(x => L1.Contains(x.Key))
but i got a dictionary of 2 rows with empry string in key
and value
.
Please advise.
Upvotes: 3
Views: 1689
Reputation: 1796
There are multiple ways to achieve what you need
In case all keys of D1 are present in L1 without mutating D1
Dictionary<string, string> D2 = new Dictionary<string, string>();
L1.ForEach(x => D2[x] = D1[x]);
OR
var D2 = L1.ToDictionary(el => el, key => D1[key]);
Safe option:
var D2 = D1.Keys.Intersect(L1).ToDictionary(key => key, key => D1[key]);
and even more, depends on your creativity
Note that this is slow for big list and dictionary
D1.Where(x => L1.Contains(x.Key))
Upvotes: 1
Reputation: 2316
You can use some thing like this :
Dictionary<string, int> dictionary = new Dictionary<string, int> {{"A", 1}, {"B", 2}, {"C", 3}};
List<string> list = new List<string> {"A","B"};
var result = dictionary.Where(x => list.Contains(x.Key)).ToList();
or
var result = dictionary.Where(x => list.Contains(x.Key)).ToDictionary(x=>x.Key,x=>x.Value);
Upvotes: 2