NutsAndBolts
NutsAndBolts

Reputation: 429

Filter dictionary on the basis of key value present in list

I have a dictionary D1 like this

enter image description here

and a list L1 like this

enter image description here

I want to have a dictionary like this (Filtering those key-value pairs whose key is present in the list )

enter image description here

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

Answers (2)

Andriy Kizym
Andriy Kizym

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

Amirhossein Yari
Amirhossein Yari

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

Related Questions