C#DataTable 使用GroupBy方法的lamda 表达式和Linq语句写法

DataTable ds = new DataTable();

//1、lamda 表达式写法(推荐)
var result = ds.AsEnumerable().GroupBy(s => new{Year = s.Field<int>("Year"), Month = s.Field<int>("Month"), Day = s.Field<int>("Day")});

//2、Linq写法 最终编译器会把它转化为lamda表达式
//var result = from s in ds.Tables[0].AsEnumerable()
             group s by new { Year = s.Field<int>("Year"), Month = s.Field<int>("Month"), Day = s.Field<int>("Day") } into temp

            select temp;

 

//DataTable 使用GroupBy方法需要注意result为IGrouping<int,DataRow>类型
foreach (var thisGroup in result)
        {
            foreach (var row in thisGroup)
            {
                //遍历当前这组的所有row
            }
        }

posted @ 2016-10-28 10:49  (john_zhang)  阅读(6735)  评论(0编辑  收藏  举报