Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract a subset of a dictionary into another one in C#?

Tags:

c#

c#-4.0

I want to filter out some dictionary pairs I do not need for further processing. Check this sample code out:

static void Main(string[] args) {     var source = new Dictionary<string, dynamic>();      source.Add("number", 1);     source.Add("string1", "One");     source.Add("string2", "Two");     source.Add("string3", "Three");      var onlyStrings = source.Where(s => s.Key != "number").ToDictionary(s => s.Key); } 

In this case, onlyStrings is a Dictionary<string, KeyValuePair<string, object>>

but I want onlyStrings to have the following pairs (a subset of the source dictionary):

  • Key: "string1", Value: "One"
  • Key: "string2", Value: "Two"
  • Key: "string3", Value: "Three"

What is the best way to get such result?

like image 498
Lenin Avatar asked Jun 20 '13 01:06

Lenin


1 Answers

There is an overload to the ToDictionary method that also allows for an elementSelector delegate:

var onlyStrings = source.Where(s => s.Key != "number")                         .ToDictionary(dict => dict.Key, dict => dict.Value); 
like image 52
Dan Teesdale Avatar answered Oct 07 '22 17:10

Dan Teesdale