【发布时间】:2011-05-02 04:49:03
【问题描述】:
例如,我有一个Element 类型的通用列表。
public class Element
{
public string Country { get; set; }
public string City { get; set; }
public int Population { get; set; }
}
有以下数据。
var elements = new List<Element>
{
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country A", City = "Barrie2", Population = 12 },
new Element { Country = "Country A", City = "Barrie2", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country D", City = "Essex", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country D", City = "Essex", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 }
};
基本上,我想要按国家和城市分组的人口总数。
类似的东西。
Country A | Barrie | `running total for Barrie`
Country A | Barrie2 | `running total for Barrie2`
| | `total for Country A`
Country D | Essex | `running total for Essex`
| | `total for Country D`
| | `total for everything`
我在任何地方都找不到扩展(我说扩展是因为我计划多次使用汇总),所以我想我会试一试。所以我从这个简单的查询开始。
var groupedElements = elements
.GroupBy(x => new { x.Country, x.City })
.Select(x => new { Country = x.Key, City = x.Select(xx => xx.City), Population = x.Sum(xx => xx.Population) })
.ToList();
此查询按预期工作,所以我认为我在正确的轨道上。接下来我想我必须弄清楚groupedElements 中的哪个属性是聚合的,因为这就是我们要做汇总的内容。我该如何做到这一点?或者也许我可以有一个参数让我指定我希望在哪个列上执行聚合函数。
【问题讨论】:
-
您期望结果中的项目的类型是什么?
-
我想我可以使用相同的类型。
-
你的意思是
total for Country B?running total for Country B似乎不太清楚。看来您想要的序列中的项目类型逻辑上不应该是相同的具体类型。 -
是的,你是对的。自从小组完成后,它不应该是一个累计。
-
我想了想,你说得对。将汇总结果放在不同的类中更有意义。