Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

linq - how do I sort a collection with child property?

I should sort parent based on a field of child.

sample code;

IQueryable<Parent> data = context.Parents.Include(o=>o.Children);

//Child has a member (string) Name.

question: how can I sort Parent by Children Names.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your question is somewhat confusing, since first of all, it is tagged both with Entity Framework and LINQ-to-SQL. Which ORM are your actually using?

Secondly, and more to the point, you say that you want to "sort Parent by Children Names". Which child name do you want to sort by? You do realize that you can't compare a list of names to another list of names and decide which one should come before the other?

So if I assume you want to sort by the child name that comes first lexicographically, your solution would be the following (@Paul was close on this one, but you need to specify the property you are sorting by):

context.
Parents.
OrderBy(p => p.
             Children.
             OrderBy(c => c.Name).Select(c => c.Name).FirstOrDefault()
       );

In this case, consider the following setup. Parent PA has children CB and CD while parent PB has children CC and CA. As a result of the sorting, parent PB will come first in the sorted list, since child CA will be used as the "main" child for PB, while CB will be the "main" child for PA. If that's not the behavior you are looking for, please provide an example and a clearer description.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...