12

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.

Nuri YILMAZ
  • 4,291
  • 5
  • 37
  • 43

2 Answers2

44

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.

Yakimych
  • 17,612
  • 7
  • 52
  • 69
5

You can take one of the children names to sort by, probably select it by doing the corresponding sorting?

Something like:

IQueryable<Parent> data = context.Parents.OrderBy(
     p=>p.Children.OrderBy(chi => chi.Name).FirstOrDefault());
Paul
  • 1,879
  • 1
  • 23
  • 44
  • hi Paul. this linq throwed exception; "DbSortClause expressions must have a type that is order comparable. Parameter name: key" – Nuri YILMAZ Jul 07 '11 at 23:05
  • Can you probably try the approach described here: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/3b26c018-a6e5-4cf4-9547-744991ff5ada – Paul Jul 07 '11 at 23:19
  • @NuriYILMAZ that's because after `FirstOrDefault()` you need to get the property or column as well such as `FirstOrDefault().MyProperty1`. – Idrees Khan May 31 '16 at 06:52