Practical Approach of Converting DataTable to Generic Dictionary Using LINQ

In this article I will show how to convert a DataTable to a Generic Dictionary<K,T>.


Step 1: Used Namespaces:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Data;

Step 2: Create a DataTable and add DataColumns to it:

DataTable dtTable = new DataTable();
dtTable.Columns.Add(new DataColumn("Company", typeof(System.String)));
dtTable.Columns.Add(new DataColumn("Product", typeof(System.String)));

dtTable.Columns.Add(new DataColumn("IsLive", typeof(System.Boolean)));

Step 3: Add rows to the DataTable:

DataRow dr = dtTable.NewRow();

dr["Company"] = "Microsoft";

dr["Product"] = "VisualStudio";

dr["IsLive"] = true;

 

dtTable.Rows.Add(dr);

 

dr = dtTable.NewRow();

dr["Company"] = "Microsoft";

dr["Product"] = "Sql Server";

dr["IsLive"] = true;

 

dtTable.Rows.Add(dr);

Step 4: Convert a DataTable to a Generic Dictionary<K,T> :

//Filter the required data from datatable.

Dictionary<String, String> dic = (from order in dtTable.AsEnumerable()

where order.Field<Boolean>("IsLive") == true

select new 

{

   //Get the specific Field from the datatable.

     company = order.Field<String>("Company"),

     product = order.Field<String>("Product")

}).AsEnumerable()

.ToDictionary(k => k.product, v => v.company);

Step 5: Explanation of the above snippet:

1. Convert DataTable As Enumerable.

   from order in dtTable.AsEnumerable()

2. Filter using the required column.

   where order.Field<Boolean>("IsLive") == true

3. Selecting the require field and add it as Enumerable.

   select
new
  
{
   //Get the specific Field from the datatable.
     
company = order.Field<String>("Company"),
      product = order.Field<String>("Product")
   }).AsEnumerable()

4. Convert Enumerable into Dictionary

   .ToDictionary(k => k.product, v => v.company);

Thanks for reading this article. Have a nice day.