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

C#LinqDictionaryLinq to-Objects

C# Problem Overview


I have the following dictionary:

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

I want to filter the dictionary's items and reassign the result to the same variable:

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

How can I return the result as a dictionary from the same type [<int,string>] ?

I tried ToDictionary, but it doesn't work.

C# Solutions


Solution 1 - C#

ToDictionary is the way to go. It does work - you were just using it incorrectly, presumably. Try this:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHomamView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow