qoDoq
qoDoq

Reputation: 5

How to sort array by enum value

I have an array and one of its elements uses enum. I want to sort the array by enum.

public enum EnumList
    {
        Spring,
        Summer,
        Fall,
        Winter,
        Unknown
    };

My array looks like this:

 Class1[] arr = new class1[7];

        arr[0] = new class1(101, "Some string", Class1.EnumList.Spring, 100, DateTime.Parse("10/13/2008"));
 .
 .
 array continues..

How do I sort by enum value?

Upvotes: 0

Views: 969

Answers (2)

Joelius
Joelius

Reputation: 4329

You can use IEnumerable.OrderBy.

If you sort by an enum-value it will look at the underlying type (usually int) and sort by that. This means the best solution would just be like this:
arr.OrderBy(c => c.TheEnumProperty);

This method will return a sorted IEnumerable which you can cast back to an array with IEnumerable.ToArray.

Upvotes: 3

Shad
Shad

Reputation: 1219

Something like

var sortedByEnum = arr.GroupBy(x => x.enum).OrderBy(group => group);

Upvotes: 0

Related Questions