如何基于子集合属性对集合进行排序

时间:2010-08-12 20:04:40

标签: linq sorting c#-3.0 lambda sql-order-by

我想基于子集合属性对集合进行排序。

//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;}
}

以下仅用于测试目的,我正在准备我的每个人的薪水内部集合的人员集合:

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 });

现在我们要对people集合进行排序,但是使用它们的内部集合SalaryValue作为参数。

如何对List进行排序,但在Salaries内部集合上使用LINQ / Lambda表达式?

所以我会:

PersonName: Johanna, SalaryValue=30000, SalaryYear=2010
PersonName: Johanna, SalaryValue=40000, SalaryYear=2011
PersonName: Junior, SalaryValue=70000, SalaryYear=2010
PersonName: Junior, SalaryValue=80000, SalaryYear=2011

2 个答案:

答案 0 :(得分:8)

对我来说,这看起来像是:

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);
}

请注意,您并没有真正对的集合进行排序 - 您正在对(人员,工资)的集合进行排序,这就是拥有两个from的扁平化效果条款确实。

(以上不会提供完全相同的输出,但是一旦你得到了这个人和他们的薪水,你就可以获得其他值。)

答案 1 :(得分:2)

看起来Jon的逻辑是正确的,但示例代码与OP不匹配。它应该更像是这样:

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);
}