本文介绍了<将DataTable存储到列表中>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好朋友,
我想将DataTables数据存储到List< dictionary>< string,object>中.每个库仑名称均表示为键,而值则表示为列的值.
我想要为DataTable中的每一行添加新字典.我不想对该操作使用任何循环语句.
请帮助我.
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.
推荐答案
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
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());
这篇关于<将DataTable存储到列表中>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!