2014-09-24 165 views
1

我想總結基於studentId組總和的LINQ to SQL

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(); 

的DayDifference我嘗試下面的代碼

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 

回答

2

這應該創建一個匿名類型的集合,包含每個 「密鑰」(StudentId),以及 「DayDifference」 值的每個StudentId總和:

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

謝謝! :) 希望如果你能分享你的收藏本書/博客文章linq – 2014-09-24 06:17:38

+1

@vignesh我發現這個網頁從MSDN是一個很好的資源:[101 LINQ示例](http://code.msdn.microsoft .com/101-LINQ-Samples-3fb9811b) – 2014-09-24 06:28:39

+0

非常感謝:) – 2014-09-24 06:59:52