代码之家  ›  专栏  ›  技术社区  ›  chum of chance

如何对linq中的子列表求和?

  •  5
  • chum of chance  · 技术社区  · 14 年前

    我有:

    public class List1 {
    public List<List2> List2 { get; set; }
    }
    
    public class List2 {
    public int TotalUnits { get; set; }
    }
    

    在我看来 List<List1> ,所以我想做如下事情:

    <%= Model.List1.Where(x.List2.Any()).Sum(x=>x.TotalUnits) .%>
    

    2 回复  |  直到 14 年前
        1
  •  13
  •   jball    14 年前

    你想得到所有 TotalUnits List2 实例?如果是,请执行以下操作

    <%= Model.List1.SelectMany(x => x.List2).Sum(x => x.TotalUnits) %>
    

    这就是工作原理

    Model.List1.SelectMany(x => x.List2)
    

    这需要 List<List1> 把它变成 IEnumerable<List2> . SelectMany 类似于 Select

    .Sum(x => x.TotalUnits)
    

    这就是 总单位 清单2 .

    class 关键字)

    public int TotalUnits { get; set;}
    
        2
  •  2
  •   recursive    14 年前

    如果我没听错的话,你在找这样的东西:

    Model.List1.Where(x => x.List2.Any()).Select(x => x.List2.Sum(y => y.TotalUnits))