Using LINQ with Generic Dictionary in C#

Here is quick example for how to manipulate a Dictionary object for some constraint and get a new Dictionary Object from that, using LINQ.

Suppose we have a Dictionary as follows, which hold some of the values which might be null

 Dictionary<string, string> dictionaryWithNullValues = new Dictionary<string, string>();

Adding Items to Dictionary

            dictionaryWithNullValues.Add("one", "one");
            dictionaryWithNullValues.Add("two", null);
            dictionaryWithNullValues.Add("three", "three");
            dictionaryWithNullValues.Add("four", "four");
            dictionaryWithNullValues.Add("five", null);

Problem: we need a new dictionary object, almost same as the old one, but without the null values, from the old dictionary. Here is how we do this, using my beloved LINQ

   dictionaryWithoutNullValues =
   .Where(d => d.Value != null)
   .ToDictionary(s => s.Key, s => s.Value);

To check the difference between both Dictionary Objects and verify, if this has worked, call the following properties on both old and new Dictionary Objects

Console.WriteLine("OldDictionary Keys: " + dictionaryWithNullValues.Keys.Count);
Console.WriteLine("OldDictionary Values: " + dictionaryWithNullValues.Values.Count);

Console.WriteLine("NewDictionary Keys: " + dictionaryWithoutNullValues.Keys.Count);
Console.WriteLine("NewDictionary Values: " + dictionaryWithoutNullValues.Values.Count);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s