如何基于子集合属性对集合进行排序 [英] How to sort a collection based on a subcollection property

查看:73
本文介绍了如何基于子集合属性对集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to sort a collection based on a 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;}
}

下面仅出于测试目的,我正在准备我的个人集合,每个内部都有Salaries内部集合:

Below just for testing purpose, I'm preparing my collection of person with Salaries inner collections each one:

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

现在,我们要对人员集合进行排序,但要使用其内部集合SalaryValue作为参数.

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

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

How can I sort List but using LINQ / Lambda expressions on Salaries inner collection?

所以我会:

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

推荐答案

对我来说,看起来像:

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

请注意,您并不是真正在对 people 进行排序-在对(person,salary)的排序进行排序,这就是具有两个from子句的扁平化作用

Note that you're not really sorting a collection of people - you're sorting a collection of (person, salary), which is what the flattening effect of having two from clauses does.

(以上内容不会提供完全相同的输出,但是一旦您获得了此人及其薪水,就可以得到其他值.)

(The above won't provide exactly the same output, but once you've got the person and their salary, you can get at the other values.)

这篇关于如何基于子集合属性对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆