How to sort a collection based on a subcollection property

I would like to sort the collection based on the subcollection property.

//the subcollection public class Salary { public int SalaryId {get;set;} public int SalaryYear {get;set;} public double SalaryValue {get;set;} //this is the field we want to sort the parent collection "Person" } //the main collection public class Person { public int PersonId {get;set;} public string PersonName {get;set;} public List<Salary> Salaries {get;set;} } 

Below for the purpose of testing, I am preparing my collection of people with internal salary collections each:

 List<Person> people = new List<Person>(); //add two salaries for Junior people.Add(new Person { PersonId = 1, PersonName = "Junior" }); people[0].Salaries.Add(new Salary { SalaryId=1, SalaryYear=2011, SalaryValue=80000 }); people[0].Salaries.Add(new Salary { SalaryId=2, SalaryYear=2010, SalaryValue=70000 }); //add two salaries for Johanna people.Add(new Person { PersonId = 2, PersonName = "Johanna" }); people[0].Salaries.Add(new Salary { SalaryId=3, SalaryYear=2011, SalaryValue=40000 }); people[0].Salaries.Add(new Salary { SalaryId=4, SalaryYear=2010, SalaryValue=30000 }); 

Now we want to sort the collection of people, but using their internal SalaryValue collection as a parameter.

How can I sort the list, but using LINQ / Lambda expressions in the internal Salaries collection?

So, I would:

 PersonName: Johanna, SalaryValue=30000, SalaryYear=2010 PersonName: Johanna, SalaryValue=40000, SalaryYear=2011 PersonName: Junior, SalaryValue=70000, SalaryYear=2010 PersonName: Junior, SalaryValue=80000, SalaryYear=2011 
+6
sorting lambda linq sql-order-by
source share
2 answers

For me it looks like this:

 var query = from person in people from salary in person.Salaries orderby salary.SalaryValue select new { person, salary }; foreach (var pair in query) { Console.WriteLine(pair); } 

Please note: you do not sort the collection of people - you sort the collection (person, salary), which makes the effect of smoothing the two sentences from .

(The above will not give exactly the same result, but as soon as you get the person and his salary, you can get other values.)

+8
source share

It seems that John's logic is correct, but the sample code does not match the OP. This should probably be more:

 var query = from person in people from salary in person.Salaries orderby salary.SalaryValue select new { person.PersonName, salary.SalaryValue, salary.SalaryYear }; foreach (var tuple in query) { Console.WriteLine(tuple); } 
+2
source share

All Articles