How to sort a collection based on a subcollection property

我的梦境 提交于 2019-12-05 07:58:28

To me, that looks like:

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

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 looks like Jon's logic is correct, but the sample code doesn't match the OP's. It should probably be more like this:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!