一、遍历DataTable
已存在一个DataTable,其中字段名为
ID(int),Name(string),Company(string),CreatedDate(DateTime)
对应此表的class为:
public class ClientStruct
{
public string ID { get; set;};
public string Name {get; set;};
public string Company { get; set;};
public string CreatedDate { get; set;};
}
遍历DataTable,取出所有的ID
List<string> lstID = (from a in dtTable.AsEnumerable() select a.Field<Int32>("ID").ToString()).ToList<string>();
if (dtTable != null && dtTable.Rows.Count > 0)
{
List<ClientStruct> list = (from a in dtTable.AsEnumerable()
orderby a.Field<string>("Company")
select new ClientStruct
{ ID = a.Field<Int32>("ID").ToString(),
Name = a.Field<string>("Name"),
Company = a.Field<string>("Company"),
CreateDate = a.Field<DateTime>("CreatedDate").ToString("yyyy-MM-dd") }).ToList<ClientStruct>();
}
二、遍历DataTable,并将上面的List结果存储到Dictionary中:
希望得到Dictionary<string, ClientStruct>(),string为ClientStruct中的Company
Dictionary<string, ClientStruct> dictionary = list.ToDictionary(p => p.Company);
三、遍历DataTable并将其中两个字段的内容存储到Dictionary中:
{
}
Dictionary<string, string> dic = dtTable.AsEnumerable().ToDictionary(v => v["Company"].ToString(), t => t["CreateDate"].ToString("yyyy-MM-dd"));
public class ProjectStruct
{
Dictionary<string, ProjectStruct> lstRet = new Dictionary<string, ProjectStruct>(); public string ProjectID { get; set;}
public string ProjectName { get; set; }
public int Status { get; set; }
}
//dtTable为已经从数据库取得的结果
lstRet = dtTable.AsEnumerable().ToDictionary(v => v["Name"].ToString(),
t => new ProjectStruct
{
PM = t["Manager"].ToString(),
ProjectID = t["ID"].ToString(),
ProjectName = t["Name"].ToString(),
Status = Public.CastInt32(t["Status"])
});
四、选择特定数据:
Dictionary<string, int> dic = new Dictionary<string,int>();
dic.Add("test1",1);
dic.Add("test2", 2);
return (from p in dic where p.value > 0 select new {
mykey = p.Key, myvalue = p.Value
}).ToDictionary(k=>k.mykey, v=>v.myvalue);
五、Dictionary之求和:
(1)创建泛型字典students(类型为Dictionary<int,Student1>),并添加4个Student1类型的元素,元素的键值分别为1~4。
(2)使用LINQ查询泛型字典students中的所有元素,并按照元素的总分的升序排序。查询结果保存在values变量中。
(3)把查询结果(学生姓名及总成绩)输出到Web表单中。
具体实现代码如下:
private void DictionaryQuery()
{
}
注意到,本例中在查询中利用了聚合查询之一,即Sum操作,求出当前学生的总分。
本例的输出结果如图所示。