Practical approach of Converting DataTable to Generic Dictionary<K, T> using LINQ

Step 1: Used Namespaces:

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

Step 2: Create 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 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 DataTable to 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);

Split Up of Above Snippet:

Step 1: Convert DataTable As Enumerable

from order in dtTable.AsEnumerable()

Step 2: Filter using the required column

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

Step 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()


Step 4: Convert Enumerable into Dictionary

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

Thanks for reading this blog. Have a nice day.