Clarence Klopfstein
Clarence Klopfstein

Reputation: 4852

Orderby a HashSet in an Object in Linq

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.

Upvotes: 0

Views: 2424

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233150

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;

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500835

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.)

Upvotes: 4

Related Questions