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.
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