Blog

Practical approach of Converting DataTable to Generic Dictionary using LINQ

Posted by Lajapathy Arun Blogs | LINQ Apr 13, 2012
In this blog I will show How to Convert DataTable to Generic Dictionary<K,T>.
Download Files: DataTableToDic.rar

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.
 

post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter