Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello Friends,
I want to store DataTables data in to a List<dictionary><string,object>. Each coulumn name indicates as key and value indicate as column's value.

I want new dictionary for each row in DataTable. I don't want to use any looping statement for this operation.

plz help me.
Posted

The data of DataTable can be converted as a List of Dictionary<string,object> where each row of the DataTable is represented as an element of type Dictionary in this List . Each column value within the Dictionary is referenced by the Column name(as given in DataTable), as a key as shown below
C#
DataTable amounts = new DataTable();
amounts.Columns.Add("Month", typeof(string),null);
amounts.Columns.Add("Name", typeof(string),null);
amounts.Columns.Add("Amout", typeof(int),null);

amounts.Rows.Add("March","John",0);
amounts.Rows.Add("April","Ishan",25);
amounts.Rows.Add("May","Raman",50);
amounts.Rows.Add("March","Sheron",0);
amounts.Rows.Add("March","Ramesh",75);

List<dictionary<string,object>> amountsDic = 
	amounts.AsEnumerable().Select (dr => {
		var dic = new Dictionary<string,object>();
		dr.ItemArray.Aggregate(-1,(int i, object v) => {
			i+=1; dic.Add(amounts.Columns[i].ColumnName,v); 
			return i;
		}); 
		return dic;
	}).ToList();

//amounts DataTable
//
//Month Name Amout
//March John 0 
//April Ishan 25 
//May Raman 50 
//March Sheron 0 
//March Ramesh 75 
//  
//List<dictionary><string,object>> amountsDic
//
//Key Value 
//Month March 
//Name John 
//Amout 0 
//
//Key Value 
//Month April 
//Name Ishan 
//Amout 25 
// 
//Key Value 
//Month May 
//Name Raman 
//Amout 50 
// 
//Key Value 
//Month March 
//Name Sheron 
//Amout 0 
// 
//Key Value 
//Month March 
//Name Ramesh 
//Amout 75 
 
Share this answer
 
v3
C#
DataTable dt = ds.Tables[0];
var columns = dt.Columns.Cast<datacolumn>();
list_ds.AddRange(dt.AsEnumerable().Select(dataRow => columns.Select(column =>
      new { Column = column.ColumnName, Value = dataRow[column] })
      .ToDictionary(data => data.Column, data => data.Value)).ToList());
 
Share this answer
 
v2
Comments
VJ Reddy 18-May-12 9:48am    
Good solution. 5!
list_ds.AddRange( is to be replaced by var list_ds = as .ToList() is used.
VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Dim i As Integer
  Dim fs As System.IO.FileStream
  Dim sw As System.IO.StreamWriter
  fs = New System.IO.FileStream("C:\Documents and Settings\Zbho\My Documents\example.txt", IO.FileMode.Open)
  sw = New System.IO.StreamWriter(fs)
  For i = 0 To ListView1.Items.Count - 1
  sw.WriteLine(ListView1.Items(i).SubItems(ColumnHeader1.Index).Text)
  Next
  sw.Close()

  End Sub
 
Share this answer
 
If you have make an object that has got same properties as the column names then you can easily do that by using the following extension method.
C#
public static List<t> ToList<t>(this DataTable table) where T : new()
        {
            List<propertyinfo> properties = typeof(T).GetProperties().ToList();
            List<t> result = new List<t>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<t>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<t>(DataRow row, List<propertyinfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (row.Table.Columns.Contains(property.Name))
                {
                    if (row[property.Name] != DBNull.Value)
                        property.SetValue(item, row[property.Name], null);
                }
            }
            return item;
        }</propertyinfo></t></t></t></t></propertyinfo></t></t>


then you can simply call

Let dt your datatable.
dt.ToList<classname>()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900