简体   繁体   中英

GroupBy in Enumerable method

I want to make a list of Report class from persons list with 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() //????
});

There is something wrong in select statement, how can I count a sum of ages?

You need to specify which property to sum:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM