How do I sort a collection with a child property?

I have to sort the parent based on the field of the child.

sample code;

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

// The child has a member (string) Name.

question: how can I sort the parent names of the children.

+4
source share
2 answers

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

Secondly, and more than that, you say you want "sort Parent by Children Names" . What child name do you want to sort? Do you understand that you cannot compare a list of names with another list of names and decide which one should be present before the other?

So, if I assume that you want to sort the name of the child, which will be the first lexicographically, your solution will be as follows: (@Paul was close to this, but you need to specify the property that you are sorting):

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

In this case, consider the following setting. Parent PA has children CB and CD , and parent PB has children CC and CA As a result of the sort, the parent PB will be the first in the sorted list, since the child CA will be used as the "primary" child for PB , while CB will be the primary "child" for PA . If this is not the behavior you are looking for, provide an example and a clearer description.

+27
source

You can take one of the names of the children to sort, perhaps select it by performing the appropriate sorting?

Sort of:

 IQueryable<Parent> data = context.Parents.OrderBy( p=>p.Children.OrderBy(chi => chi.Name).FirstOrDefault()); 
+3
source

All Articles