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 =
   dictionaryWithNullValues
   .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);

Linq-to-SQL, Linq-to-DataSet and Linq-to-Entities

LINQ to SQL is an O/RM (object relational mapping) implementation that was provided in the .NET Framework “Orcas” (.NET Framework version 3.5) release.

It allows us to model a relational database using .NET classes and query those models using LINQ notation / syntax. We can query the database and perform all operations like update, insert and delete etc.

As per MSDN: ” It provides a run-time infrastructure for managing relational data as objects”

Linq-to-DataSets is just LINQ, but it is used to query against the ADO.NET DataSets. As per MSDN : “LINQ to DataSet makes it easier and faster to query over data cached in a DataSet object”.

Linq-to-Entities is better and provides more flexibility and is usable with many types of data sources and is not limited to SQL Server only, like Linq-to-SQL is. It uses Entity Framework in the background, as the ORM.