在linq到sql的组和总和

时间:2014-09-24 05:02:26

标签: c# asp.net linq

我想根据studentId总结DayDifference

 List<Timeliness> studentData = (from redt in RoundEndDateTable.AsEnumerable()
                                                join st in Activity on redt.Field<string>("strActivityName") equals st.ActivityName
                                                orderby (DateTime.Parse(redt.ItemArray[1].ToString()) - DateTime.Parse(st.RewardType.ToString())) descending
                                                select new Timeliness
                                                {

                                                    DayDifference = int.Parse((DateTime.Parse(redt.ItemArray[1].ToString()) - DateTime.Parse(st.RewardType)).ToString().Split('.')[0]),
                                                    StudentId = st.AssociateId.ToString()
                                                }).ToList();

我尝试了以下代码

var groupedCustomerList = studentData
    .GroupBy(u => u.StudentId)
    .Select(grp => grp.ToList())
    .ToList();

不确定在上述代码中添加总和的位置

在第一个查询中,我正在重复学生ID

例如:

[0]  - studentid:123 DayDifference:16
[1]  - studentid:123 DayDifference:8
[2]  - studentid:121 DayDifference:16

我需要

[0]  - studentid:123 DayDifference:24
[2]  - studentid:121 DayDifference:16

1 个答案:

答案 0 :(得分:2)

这应该创建一个匿名类型的集合,包含每个&#34; Key&#34; (StudentId),以及&#34; DayDifference&#34;的总和。每个StudentId的值:

var result =
    studentData.GroupBy(u => u.StudentId)
               .Select(grp => new { Id = grp.Key, TotalDiff = grp.Sum(x => x.DayDifference) })
               .ToList();