2015-02-07 36 views
2

我想的GroupBy在可枚举法

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语句,我怎么能算年龄的总和?

+0

看一看这个答案http://stackoverflow.com/questions/19285443/group-by-count-and-lambda-expression – CheGueVerra 2015-02-07 15:48:32

回答

4

您需要指定要总结哪个属性:

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