我有几个袋子,每个袋子装满了多个苹果容器,每个容器可能有0个或更多的苹果。
public class Bag
{
public List<Container> Containers { get; set; }
}
public class Container
{
public List<Apple> Apples { get; set; }
}
public class Apple
{
public double Weight { get; set; }
}
如果我有一个集合List<Bag> bags
,如何在C#中通过Linq计算所有苹果的总重量?
答案 0 :(得分:1)
var bags = ...;
var total = bags.Sum(b => b.containers.Sum(c => c.apples.Sum(a => a.weight)) );
编辑:按要求添加说明(尽管代码本身就是解释性的,解释是多余的):
阅读从最里面到外面的代码,我们正在总结苹果&#39;每个容器的重量,然后是容器&#39;总和,然后最后袋子&#39;总计:它看起来像这样:
Bag1
+-----Container1
| +------Apple 10
| +------Apple 20
|----------------------------------
| Container Total 30
+-----Container2
| +------Apple 11
| +------Apple 22
| +------Apple 33
|----------------------------------
| Container Total 66
|----------------------------------
| Bag Total 96
... Other bags
|----------------------------------
Grand total ...
答案 1 :(得分:0)
List<Bag> bags = ...
List<Container> containers = bags.SelectMany(bag => bag.Containers);
List<Apple> apples = containers.SelectMany(container => container.Apples);
var totalWeight = apples.Sum(apple => apple.Weight);
SelectMany
扩展方法用于在执行总和之前将二维数据结构展平为一维结构
答案 2 :(得分:-1)
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Bag> bags = new List<Bag>() {
new Bag() { containers = new List<Container>() {
new Container() { apples = new List<Apple>() {
new Apple() { weight = 1.0},
new Apple() { weight = 1.2},
new Apple() { weight = 1.3}
}},
new Container() { apples = new List<Apple>() {
new Apple() { weight = 0.9},
new Apple() { weight = 1.15}
}}
}},
new Bag() { containers = new List<Container>() {
new Container() { apples = new List<Apple>() {
new Apple() { weight = 1.0},
new Apple() { weight = 1.2},
new Apple() { weight = 1.3}
}},
new Container() { apples = new List<Apple>() {
new Apple() { weight = 0.9},
new Apple() { weight = 1.15}
}}
}}
};
double total = bags.Select(x => x.containers.Select(y => y.apples.Select(z => z.weight))).SelectMany(a => a).SelectMany(b => b).Sum();
}
}
public class Bag
{
public List<Container> containers { get; set; }
}
public class Container
{
public List<Apple> apples { get; set; }
}
public class Apple
{
public double weight { get; set; }
}
}