GroupBy难以置信的实体框架

时间:2012-07-17 00:28:39

标签: .net entity-framework

在下面的代码中,detail{ User, Amount, <other fields> }的列表,如

var detail = new List<TuitionDetailItem>();

我希望perMember成为{ User, Total }的列表,其中浮点数是Amount User的总和。

var perMember = detail
    .Where(x => x.ItemType == TuitionDetailItemType.Details)
    .GroupBy(x => new { x.User, x.Amount })
    .Select(x => new { x.Key.User, Total = x.Sum(y => y.Amount) })
    .ToList();

我实际得到的只是detail的副本,没有分组或总结。

感谢您的帮助!! 埃里克

1 个答案:

答案 0 :(得分:0)

var perMember = detail
    .Where(x => x.ItemType == TuitionDetailItemType.Details)
    .GroupBy(x => x.User)
    .Select(x => new { x.Key, Total = x.Sum(y => y.Amount) })
    .ToList();

或更好(我觉得它更干净)

var perMember = from d in detail
    where d.ItemType == TuitionDetailItemType.Details
    group d by d.User into g
    select new { User = g.Key, Total = g.Sum(d => d.Amount)};