Linq 操作DataTable

来源:互联网 发布:话费流量三级分销源码 编辑:程序博客网 时间:2024/04/30 17:29
  1. class ClientStruct  
  2.         {  
  3.             public string ID = "ID";  
  4.             public string Name = "Name";  
  5.             public string Company = "Company";  
  6.             public string CreatedDate = "CreatedDate";  
  7.         }  
[csharp] view plain copy
  1. public string[,] infoArr = new string[,] { { "1""百度""baidu""201303" }, { "2""迅雷""xunlei""201302" }, { "3""谷歌""guge""201301" } };  
[csharp] view plain copy
  1. protected void LinqDataTable()  
  2.         {  
  3.             DataRow row;  
  4.             ClientStruct cs = new ClientStruct();  
  5.             DataTable dtTable = new DataTable();  
  6.             dtTable.Columns.Add(cs.ID);  
  7.             dtTable.Columns.Add(cs.Name);  
  8.             dtTable.Columns.Add(cs.Company);  
  9.             dtTable.Columns.Add(cs.CreatedDate);  
  10.             for (int i = 0; i < 3; i++)  
  11.             {  
  12.                 row = dtTable.NewRow();  
  13.                 row[cs.ID] = infoArr[i, 0];  
  14.                 row[cs.Name] = infoArr[i, 1];  
  15.                 row[cs.Company] = infoArr[i, 2];  
  16.                 row[cs.CreatedDate] = infoArr[i, 3];  
  17.                 dtTable.Rows.Add(row);  
  18.             }  
  19.   
  20.             //遍历DataTable,取出所有的ID  
  21.             List<string> lstID = (from d in dtTable.AsEnumerable()  
  22.                                   select d.Field<string>(cs.ID)).ToList<string>();  
  23.   
  24.             //遍历DataTable,将其中的数据对应到ClientStruct中:  
  25.             List<ClientStruct> list = (from x in dtTable.AsEnumerable()  
  26.                                        orderby x.Field<string>(cs.Company)  
  27.                                        select new ClientStruct  
  28.                                        {  
  29.                                            ID = x.Field<string>(cs.ID),  
  30.                                            Name = x.Field<string>(cs.Name),  
  31.                                            Company = x.Field<string>(cs.Company),  
  32.                                            CreatedDate = x.Field<string>(cs.CreatedDate)  
  33.                                        }).ToList<ClientStruct>();  
  34.   
  35.             //遍历DataTable,并将上面的List结果存储到Dictionary中:  
  36.             Dictionary<string, ClientStruct> dic = list.ToDictionary(p => p.Company);  
  37.             //p作为string键值来存储  
  38.         }  

其实关键是AsEnumerable()方法,返回一个 System.Collections.Generic.IEnumerable<T> 对象
原创粉丝点击