Tôi muốn sắp xếp bộ sưu tập dựa trên thuộc tính thu thập con.Cách sắp xếp bộ sưu tập dựa trên thuộc tính thu thập phụ
//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;}
}
Dưới đây chỉ dành riêng cho mục đích thử nghiệm, tôi đang chuẩn bị bộ sưu tập của tôi về người có lương bộ sưu tập nội mỗi người:
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 });
Bây giờ chúng ta muốn sắp xếp bộ sưu tập người, nhưng sử dụng SalaryValue bộ sưu tập bên trong của họ làm tham số.
Làm cách nào để sắp xếp Danh sách nhưng sử dụng biểu thức LINQ/Lambda về Thu nhập bên trong tiền lương?
Vì vậy, tôi sẽ có:
PersonName: Johanna, SalaryValue=30000, SalaryYear=2010
PersonName: Johanna, SalaryValue=40000, SalaryYear=2011
PersonName: Junior, SalaryValue=70000, SalaryYear=2010
PersonName: Junior, SalaryValue=80000, SalaryYear=2011
mã thiếu khởi tạo trường Danh sách lương cho một người (người [i]) –