Linq中Sum和Group的使用

var query = from c in ds.Tables[0].AsEnumerable()
            group c by c.Field<int>("Name")
            into s
            select new
            {
                ID = s.Select(m => m.Field<int>("ID").ToString()),
                Name = s.Select(m => m.Field<string>("Name").ToString()),
                Math = s.Sum(p => p.Field<decimal>("Math")),
                Chinese = s.Sum(p => p.Field<decimal>("Chinese"))
            };
            DataTable dtss = new DataTable();
            dtss.Columns.Add(new DataColumn("ID", typeof(string)));
            dtss.Columns.Add(new DataColumn("Name", typeof(string)));
            dtss.Columns.Add(new DataColumn("Math", typeof(string)));
            dtss.Columns.Add(new DataColumn("Chinese", typeof(string)));
            query.ToList().ForEach(p => dtss.Rows.Add(p.ID, p.Name, p.Math, p.Chinese ));

https://www.xuebuyuan.com/1879650.html

posted @ 2018-10-30 10:04  zhaogaojian  阅读(7628)  评论(3编辑  收藏  举报