views:

233

answers:

2

I have a pretty complex Linq statement with multiple joins, but am having a problem with an orderby statement.

I think I can reduce the question down a bit, but will expand if needed.

First my object has the following properties:

myObject.ID This is a basic Int

myObject.BrandName This is my HashSet<string>.

I need to sort my Object by the BrandName using the lowest or highest value depending on if I am sorting ascending or descending.

+3  A: 

So you mean order by the minimum or maximum value in the set? Fortunately that's easy - even if it'll perform fairly badly:

orderby myObject.BrandName.Min()

or

orderby myObject.BrandName.Max() descending

(Or vice versa, depending on what ordering you want.)

Jon Skeet
Awesome. I don't know what I like more as I dig... Linq or StackOverflow.com :-)
Clarence Klopfstein
+1  A: 

Would this work for you?

// replace with mo.BrandName.Min() to sort the other way
Func<MyObject, string> getBrand = mo => mo.BrandName.Max();

var q = from myObject in myObjects
        let b = getBrand(myObject)
        orderby b
        select myObject;
Mark Seemann
There's no need to use a "let" clause here. You do need to make it Max() or Min() rather than Max or Min though.
Jon Skeet
I thought that the OP needed the syntax as a part of a bigger expression, in which case it might have been useful to know about... Apparently not...
Mark Seemann
While not useful for me, it may help others. Thanks for the effort and info. I can't +1 you... as I have no idea if what you have will work :-)
Clarence Klopfstein
@Clarence: It would - it's basically equivalent to mine. You can still have the `Func<MyObject, string>` bit and use `orderby getBrand(myObject)` though - no need for the `let` clause unless you need the value elsewhere (in which case you might as well only find it once, of course).
Jon Skeet