c# - Enumerable 方法中的 GroupBy

标签 c# linq

我想从具有分组依据的人员列表中创建报告类列表

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语句有问题,如何计算年龄总和?

最佳答案

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

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

关于c# - Enumerable 方法中的 GroupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28383830/

相关文章:

c# - MEF 不导入根 exe 部分

c# - 字典c#的算术运算

c# - 是否可以在对 Where 的调用中调用命名方法?

c# - 具有 LinQ 相关查询的 MySQL Entity Framework 未执行

c# - 在云中将 SQL Azure 数据库从 SQL Server 2008 迁移到 2014

c# - 在 C# 中,为什么我会收到 "can' t cast double to float 错误”?

c# - 使用反射设置嵌套属性值

c# - groupby 之后的 linq 无法获取列值

c# - 从数据库加载大块数据时如何避免 OutOfMemoryException?

c# - 处理文件属性 C#