How can I filter a dictionary using LINQ and return it to a dictionary of the same type

I have the following dictionary:

Dictionary<int,string> dic = new Dictionary<int,string>(); dic[1] = "A"; dic[2] = "B"; 

I want to filter out the dictionary elements and reassign the result to the same variable:

 dic = dic.Where (p => p.Key == 1); 

How to return the result in the form of a dictionary from the same type [ <int,string> ]?

I tried ToDictionary , but it does not work.

Thanks in advance.

+57
dictionary c # linq linq-to-objects
Oct 21 2018-10-10
source share
1 answer

ToDictionary is the way to go. It really works - you used it incorrectly, presumably. Try the following:

 dic = dic.Where(p => p.Key == 1) .ToDictionary(p => p.Key, p => p.Value); 

Having said that, I assume that you really need a different Where filter, since your current one will only find one key ...

+118
Oct 21 '10 at 15:15
source share



All Articles