【问题标题】:GroupBy in Enumerable methodGroupBy 在 Enumerable 方法中
【发布时间】:2015-02-07 15:20:18
【问题描述】:

我想用 group by 从人员列表中创建一个报告类列表

class Report
{
    public string Country { get; set; }
    public double SumAge { get; set; }
}

class Person
{
    public int Age { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

var list = new List<Person>
{
    new Person {Age = 35, Country = "Spain", Name = "John"},
    new Person {Age = 45, Country = "Spain", Name = "Alex"},
    new Person {Age = 55, Country = "Hungary", Name = "Bob"},
    new Person {Age = 23, Country = "Spain", Name = "Eve"},
    new Person {Age = 39, Country = "India", Name = "Rose"},
    new Person {Age = 25, Country = "India", Name = "Peter"},
    new Person {Age = 51, Country = "Hungary", Name = "Rob"},
    new Person {Age = 23, Country = "India", Name = "Jeff"},
};
list.GroupBy(p => p.Country, p => p)
   .Select(p => new Report 
{
    Country = p.Key,
    SumAge = p.Sum() //????
});

select语句有问题,怎么计算年龄的总和?

【问题讨论】:

标签: c# linq


【解决方案1】:

您需要指定要求和的属性:

var res = list.GroupBy(p => p.Country, p => p)
    .Select(p => new Report
    {
         Country = p.Key,
         SumAge = p.Sum(x => x.Age)
    });

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多