<将DataTable存储到列表中> [英] Store DataTable in to List&gt;

查看:94
本文介绍了<将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 的数据可以转换为Dictionary<string,object>List ,其中DataTable 的每一行都表示为此List 中类型为Dictionary的元素. Dictionary 中的每个列值都由Column name引用(如DataTable中所述),如key 所示,如下所示
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
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());


通过这些链接,您可能会有所了解

http://stackoverflow.com/questions/208532/如何将数据表转换为通用列表 [ http://stackoverflow.com/questions/4104464/convert-datatable- to-generic-list-in-c-sharp [ ^ ]
go through these links you may get some idea

http://stackoverflow.com/questions/208532/how-do-you-convert-a-datatable-into-a-generic-list[^]

http://stackoverflow.com/questions/4104464/convert-datatable-to-generic-list-in-c-sharp[^]


这篇关于<将DataTable存储到列表中>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆