94

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.

Thanks in advance.

Homam
  • 21,556
  • 28
  • 104
  • 181
  • 11
    In future, if you've tried the obvious approach but found it doesn't work, please post the code you've tried. – Jon Skeet Oct 21 '10 at 15:28

1 Answers1

207

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...

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929