Abhi's den...

The piece of code which nobody cracked...

DataTable to Dictionary using LINQ

Sometimes we have to create generic dictionary from the values in datatable. Usually we will loop through all the rows in the datatable and add the relevant keys to dictionary object

 

for (int _iExRowCnt = 0; _iExRowCnt < dsReturn.Tables[0].Rows.Count; _iExRowCnt++)

{

//add some code to chek null values & other validations if any

_dictObj.Add(dsReturn.Tables[0].Rows[iExRowCnt][0].dsReturn.Tables[0].Rows[iExRowCnt][1]);

}

 

After LINQ was introduced there better way of doing the same addition.
In the following code i am creating a datatable and populaing few dummy records.

DataTable dtTable = new DataTable();dtTable.Columns.Add(new DataColumn("ColumnNo", typeof(System.String)));
dtTable.Columns.Add(
new DataColumn("controlType", typeof(System.String)));
dtTable.Columns.Add(
new DataColumn("showVal", typeof(System.Boolean)));

 

DataRow dr;

for (int i = 0; i < 10; i++)
{
dr = dtTable.NewRow();
dr[0] = dtTable.Rows.Count + 1;
dr[1] = i.ToString() +
"Value";
dr[2] =
false;
dtTable.Rows.Add(dr);
}

//In the following code I am using LINQ to create a new Dictionary<string,string>

//You can filter the data and checf for the conditions in data which you dont want in dictionary

 

var dic = (from order in dtTable.AsEnumerable()

where order.Field<Boolean>("showVal") == false

select new

{

myColumnNo = order.Field<
String>("ColumnNo"),myControlType = order.Field<String>("controlType")

}).AsEnumerable().ToDictionary(k => k.myColumnNo, v => v.myControlType);

 

This code snippet uses Enumerable.ToDictionary Method
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx

var dic will hold Dictionary<string,string> object. In the sample code it will have 10 elements

 For further reading

Posted: Dec 28 2009, 02:35 PM by cabhilash | with 4 comment(s) |
Filed under: , ,

Comments

Twitter Trackbacks for DataTable to Dictionary using LINQ - Abhi's den... [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 DataTable to Dictionary using LINQ - Abhi's den...         [asp.net]        on Topsy.com

# December 28, 2009 6:33 AM

vishal giri said:

good one helped lot

# June 9, 2010 8:01 AM

theofontane said:

This was extremly helpful! I never expected that LINQ is so powerful...

Thank you!

# December 23, 2010 5:20 AM

Karthik said:

Is there any way to compute the Dictionary object when the Columns in datatable is dynamic ?

# July 15, 2011 7:26 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)