简体   繁体   中英

How to sort a list of objects by a property of a nested list with Linq?

Let's say I have a list of groups. Each group has a list of persons. How can I sort the groups by their youngest person?

var groups = new List<Group>{groupA, groupB, groupC};

public class Group {
   public string Name {get; set;}
   public List<Person> Members {get; set;}
}

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

You can use OrderBy method with Min age of Members list of each group

var groups = new List<Group>
{
    new Group {Name = "group1", Members = new List<Person> {new Person {Age = 5}, new Person {Age = 2}}},
    new Group {Name = "group2", Members = new List<Person> {new Person {Age = 3}, new Person {Age = 4}}},
    new Group {Name = "group3", Members = new List<Person> {new Person {Age = 1}}}
};
var result = groups.OrderBy(g => g.Members.Min(m => m.Age));

It gives you the group3 (minimal Age is 1), group1 (minimal Age is 2), group2 (minimal Age is 3) order in example above

OrderBy lets you use any expression you wish, no matter how complex, so you could write

var byYongestMember = groups
    .OrderBy(g => g.Select(p => p.Age).Min());

However, this may be somewhat slow when there's a lot of people in each group, and the groups themselves are large, so you would be better off pairing up each group with the age of its youngest member, sorting the pairs, and then projecting the groups:

var byYongestMember = groups
    .Select(g => new {
        Group = g
    ,   MinAge = g.Members.Min(p => p.Age)
    })
    .OrderBy(p => p.MinAge)
    .Select(p => p.Group);

This way, figuring out the youngest member's age would happen only once per group.

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