Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Sort List of objects using OrderBy EnumValue, and Union result set?

Greetings! I want to use LINQ to query a list of objects and sort them by an enumeration value, string value then union the rest of the list sorted in a similar fashion LINQ newbie here, so be gentle.

//CTOR for my class
MyClass(id, "Name Value Here", Enum.EnumValueHere);

I create a list of these objects and want to variably sort them such that all items with Enum.EnumValue[X] are shown first in the list, sorted by Name, followed by all other items sorted in a similar fashion (almnost like a Union of result sets in SQL)

//What I have so far (only sorts the list)
List<MyClass> = (from s in MyClass orderby s.EnumValue, s.NameValue  select s).ToList();

Any Guru's out there have some LINQ Magic to share?

Thanks!


1 Answers

Not sure exactly what you mean, but could you use something like this?

// Using Color as enum just to make things clearer
class ClassyClass
{
    public string Name {get; private set;}
    public Color Color {get; private set;}
    public ClassyClass(id, string name, Color color) { ... }
}


var orderedList = collectionOfClassyClasses
            .OrderBy(x => x.Color != Color.Red) // False comes before true
            .ThenBy(x => x.Color)
            .ThenBy(x => x.Name)
            .ToList();

If collectionOfClassyClasses was some sort of collection of ClassyClass objects, then orderedList would be ordered so that all those with Color set to Red would come first, ordered by name, and then all the others ordered by color and then name. At least I think it would... haven't tested it :p Let me know if it doesn't, hehe.

like image 126
Svish Avatar answered Nov 24 '25 01:11

Svish