Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order query Results by Enum Name

Tags:

c#

enums

linq

I have a List<string> with the following entries:

"Summer", "Spring", "Winter"

I'd like to write a .OrderBy() that orders them based on this:

public enum Term {
    Spring = 0, Summer, Fall, Winter, All
}

Thus, the result I'd like to see is:

"Spring", "Summer", "Winter"

EDIT - For clarification, not every client has ALL of the available terms, but I just want consistency in the sorting of the list.

like image 936
Adam Levitt Avatar asked Apr 06 '26 18:04

Adam Levitt


2 Answers

var q = l.OrderBy (x => Enum.Parse(typeof(Term), x));
like image 100
Magnus Avatar answered Apr 09 '26 17:04

Magnus


List<string> terms = new List<string> { "Summer", "Spring", "Winter" };

var enumNames = Enum.GetNames(typeof(Term))
                    .OrderBy(s=>Enum.Parse(typeof(Term),s))
                    .ToList();

var orderedList = terms.OrderBy(s => enumNames.IndexOf(s)).ToList();
like image 23
I4V Avatar answered Apr 09 '26 18:04

I4V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!