tags:

views:

502

answers:

5

How do I order by child objects in LINQ?

Classes A, B, and C. A has a collection of B and B has a collection of C. I want to order object A by the Ordinal (int) property of C.

var query = from a in db.A
        orderby a.Bs.OrderBy(x=> x.C.Ordinal)   <--- ??
        select a;

I can't seem to figure out the orderby statement for this.

EDIT:

Sorry, my original statement was incorrect:

A has a collection of B and B holds a C object. C is not a collection.

Each A should be ordered on C's ordinal property.

ANOTHER EDIT/Solution:

I ended up doing an .OrderBy(b=>b.C.Ordinal) on the client for each B collection in A during display. That turned out better anyway since I can let the client order by anything they need to, instead of embedding that in my repository.

+2  A: 

You are trying to order by a Collection. That wont work. You need to either chose one element or aggregate a single value from the child list.

leppie
+2  A: 

You need to work out which C you're interested in.

Think of this in terms of real things - if you're trying to order parents by their children's ages, which child's age to you take into account? If you have one parent with kids of ages 1 and 5, and one parent with kids of ages 2 and 4, which should come first?

Jon Skeet
Beat me by a few seconds.
Joel Coehoorn
A: 

I will apply my american instincts and assume you want to order by the largest C.Ordinal for each A.

IEnumerable<A> result = db.As
  .OrderBy(a => a.Bs
    .Max(b => b.C.Ordinal)
  );

Edit: updated for "b.Cs is not a collection"

David B
oddly, that didn't solve it either. I ended up doing an .OrderBy(b=>b.C.Ordinal) on the client for each B collection in A during display. Turned out better anyway since the ordering is on the client tier. thanks.
ericvg
A: 

I ended up doing an .OrderBy(b=>b.C.Ordinal) on the client for each B collection in A during display. That turned out better anyway since I can let the client order by anything they need to, instead of embedding that in my repository.

ericvg
A: 

This may not be what you're looking for exactly, but it may give you some ideas:

.OrderBy( b => b.C.FirstOrDefault().Ordinal)

Remus