首页 新闻 会员 周边

统计,linq

1
悬赏园豆:20 [已解决问题] 解决于 2012-05-22 21:44

 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最好
    

JustYong的主页 JustYong | 初学一级 | 园豆:7
提问于:2012-05-22 16:56
< >
分享
最佳答案
1
    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) 语法?

收获园豆:20
无之无 | 大侠五级 |园豆:5095 | 2012-05-22 17:05
其他回答(1)
1

    var result = from m in stus
                         group m by m.colleage into p
                         select new { ID = p.Key, score =p.Sum(m=>m.score)};

無限遐想 | 园豆:3740 (老鸟四级) | 2012-05-22 17:42

赞赏你的答案!

支持(0) 反对(0) 待吾伐楚乃可 | 园豆:211 (菜鸟二级) | 2012-05-22 19:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册