views:

19

answers:

1

Hi All,

Trying to use Linq with some Entity objects to do a crafty query here. Hoping for some help with a point I'm having a hard time finding decent documentation on:

Basically, I'm trying to use OrderBy to order against the child of an object I'm querying against. The difficult part is that the object has multiple children, and based on the object's type, I need to use one set of a children or another set of children to order by.

To clarify:

A can come in two types: i, or ii

If A is of type i, then I need to order by D: i.e, A has a B, which has many Cs, which has many Ds.

If A is of type ii, then I need to order by F: ie. A has an E, which has many Fs.

So the question is, how can I order by D and F, from A?

I'm hoping for something like:

IQueryable<AObject> aObj = query.OrderBy(aObject=> aObject.Type==i? aObject.B.C.D : aObject.E.F).Skip(offset).Take(limit).AsQueryable();

Of course, I'm also just confused as to how to order the D's, when C has a collection of Ds

Thoughts? And thanks in advance!

+1  A: 

You need to use an aggregate function such as Min or Max to pick a value that represents the collection and use that value for the ordering. For example:

IQueryable<AObject> aObj = query.OrderBy(aObject =>
    aObject.Type==i ?
    aObject.B.Cs.Max(c => c.Ds.Max(d => d.Foo)) : 
    aObject.E.Fs.Max(f => f.Bar)
).Skip(offset).Take(limit).AsQueryable();
Mark Byers
Hm, can you explain the use of Max? Wouldn't Max just return the largest D, and then by ordered by the largest D? To use numbers, if the largest D was 10, wouldn't OrderBy by ordered by 10? That makes no sense to me...
AlishahNovin
@AlishahNovin: It's not "ordered by 10", it's ordering by the result of the lambda function. The function is evaluated once per element so for one element you might get 10, the next element give 12, the next 9, etc... Then these values will be used to order the elements (in this case 9, 10, 12).
Mark Byers
Ahh, that makes sense then. Thanks for clearing that up!
AlishahNovin