LINQ - Sort List of objects using OrderBy EnumValue, and Union result set?
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.
Admin
Updated on July 16, 2020Comments
-
Admin almost 4 years
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!
-
Admin almost 15 yearsThank's for your response. Your edit proved to be correct, in that false is evaluated b4 true...your solution works great, thanks a ton!
-
Lemon almost 15 yearsGreat to hear it worked out :) I'll remove the edit and fix the code so that it is correct instead =)