按年龄分组人员

时间:2019-01-12 15:07:52

标签: c# .net linq

这是PersonAgeGroup类:

public class PersonAgeGroup
{
    public int Age { get; set; }
    public IEnumerable<Person> Persons { get; set; }
}

这是Person类:

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

    public override bool Equals(object obj)
    {
        if (!(obj is Person other)) return false;

        return other.Name.Equals(Name) && other.Age.Equals(Age);
    }
}

因此,我们的意图是将Person的列表按其年龄分组到PersonAgeGroup的列表中,到目前为止,我已经明白了这一点,但是我仍然遇到了麻烦。 ages.ToList()PersonAgeGroup列表中输入了错误的列表类型:

public IList<PersonAgeGroup> GroupPersonsByAge(List<Person> persons)
{
    var results = from person in persons
        group person by person.Age
        into ages
        select new {Age = ages.Key, Persons = ages.ToList()};
    //Tip: use the "ToList" extension method to convert an IEnumerable to a List
    IList<PersonAgeGroup> people = results.ToList();
    return people;
}

3 个答案:

答案 0 :(得分:1)

按年龄分组,然后选择每个组并将其映射到PersonAgeGroup

var reuslt = persons.GroupBy(p => p.Age)
                .Select(grp => new PersonAgeGroup { Age = grp.Key, Persons = grp});

答案 1 :(得分:0)

首先,您不应该返回null。其次,在您的select语句中创建一个PersonAgeGroup实例,而不是anonymous object

例如,

var result = list.GroupBy(x=>x.Age)
                 .Select(x=> new PersonAgeGroup
                          {
                             Age= x.Key, 
                             Persons = x.ToList()
                           });

您的方法将是(消除结果变量)

public IList<PersonAgeGroup> GroupPersonsByAge(List<Person> persons)
{
    return persons.GroupBy(x=>x.Age)
                         .Select(x=> new PersonAgeGroup
                                   {
                                      Age= x.Key, 
                                      Persons = x.ToList()
                                   }).ToList();

}

答案 2 :(得分:0)

您可以直接在LINQ中创建repositories { mavenLocal() mavenCentral() } 。另外,您需要返回结果,而不是PersonAgeGroup

null

一些程序员喜欢将这两行合并为一:

public IList<PersonAgeGroup> GroupPersonsByAge(List<Person> persons) {
    var results = from person in persons
                  group person by person.Age into ages
                  select new PersonAgeGroup { Age = ages.Key, Persons = ages.ToList() };
    //Tip: use the "ToList" extension method to convert an IEnumerable to a List
    return results.ToList();
}