Monday, December 28, 2009

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

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)));
new DataColumn("controlType"typeof(System.String)));
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() + 
dr[2] = 
//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
var dic will hold Dictionary<string,string> object. In the sample code it will have 10 elements
 For further reading
Post a Comment