class ClientStruct
{
public string ID = "ID";
public string Name = "Name";
public string Company = "Company";
public string CreatedDate = "CreatedDate";
}public string[,] infoArr = new string[,] { { "1", "百度", "baidu", "201303" }, { "2", "迅雷", "xunlei", "201302" }, { "3", "谷歌", "guge", "201301" } };protected void LinqDataTable()
{
DataRow row;
ClientStruct cs = new ClientStruct();
DataTable dtTable = new DataTable();
dtTable.Columns.Add(cs.ID);
dtTable.Columns.Add(cs.Name);
dtTable.Columns.Add(cs.Company);
dtTable.Columns.Add(cs.CreatedDate);
for (int i = 0; i < 3; i++)
{
row = dtTable.NewRow();
row[cs.ID] = infoArr[i, 0];
row[cs.Name] = infoArr[i, 1];
row[cs.Company] = infoArr[i, 2];
row[cs.CreatedDate] = infoArr[i, 3];
dtTable.Rows.Add(row);
}
//遍历DataTable,取出所有的ID
List<string> lstID = (from d in dtTable.AsEnumerable()
select d.Field<string>(cs.ID)).ToList<string>();
//遍历DataTable,将其中的数据对应到ClientStruct中:
List<ClientStruct> list = (from x in dtTable.AsEnumerable()
orderby x.Field<string>(cs.Company)
select new ClientStruct
{
ID = x.Field<string>(cs.ID),
Name = x.Field<string>(cs.Name),
Company = x.Field<string>(cs.Company),
CreatedDate = x.Field<string>(cs.CreatedDate)
}).ToList<ClientStruct>();
//遍历DataTable,并将上面的List结果存储到Dictionary中:
Dictionary<string, ClientStruct> dic = list.ToDictionary(p => p.Company);
//p作为string键值来存储
}其实关键是AsEnumerable()方法,返回一个 System.Collections.Generic.IEnumerable<T> 对象
本文介绍了一种使用C#中的LINQ技术操作DataTable的方法。通过创建DataTable并填充数据,然后利用LINQ进行查询和转换,最终实现了数据的有效管理和操作。此外,还展示了如何将查询结果存储到List和Dictionary中。
431

被折叠的 条评论
为什么被折叠?



