class Stu
{
//学生学号
public string stuID{get;set;}
//学生成绩
public int score{get;set;}
//学生学院号
public string colleage{get;set;}
}
现有如下数据
List<Stu> stus = new List<Stu>()
{
new Stu(){stuID = "1", score = 1,colleage = "001"},
new Stu(){stuID = "2", score = 2,colleage = "003"},
new Stu(){stuID = "3", score = 3,colleage = "002"},
new Stu(){stuID = "4", score = 4,colleage = "002"},
new Stu(){stuID = "5", score = 5,colleage = "001"},
new Stu(){stuID = "6", score = 6,colleage = "001"},
};
现想实现如下功能:得到所有的学院以及学院学生的总成绩,类似结果如下
new Colleage(){ID= "001", score = 12}
new Colleage(){ID= "002", score = 7}
new Colleage(){ID= "003", score = 2}
有什么好的实现方法,用LIQN最好
var list = from c in stus group c by c.colleage into g select new Colleage { ID=g.Key, score = (from d in g select d.score).Sum() }; var array = list.ToArray();
没运行测验,大致就这样,你修正下。
参考:请问在Linq to sql 中,怎么使用 sql 语句中的 max(case when ... then ... else ... end) 语法?
var result = from m in stus
group m by m.colleage into p
select new { ID = p.Key, score =p.Sum(m=>m.score)};
赞赏你的答案!