Reputation: 4455
I have an enum
:
public enum Group
{
Administration = 1,
Lawyers,
PropertyManagement
Bookkeeping,
Secretariat
}
I have a List
of Group
also: List<Group>
. I need a simple way to sort the values of the list by the enum index.
So, for example, this list:
{ Group.Bookkeeping, Group.Administration, Group.Secretariat, Group.Administration }
Will become:
{ Group.Administration, Group.Administration, Group.Bookkeeping, Group.Secretariat }
(Administration first, bookkeeping second, secretariat last, like in the definition of the enum). I am looking for a simple way (maybe using linq
), without manually looping or so.
Upvotes: 0
Views: 579
Reputation: 6744
You can use Linqs OrderBy
:
List<Group> orderedGroups = groups.OrderBy(g => g).ToList();
Upvotes: 0
Reputation: 151730
An enum is basically an integral type, and its members gets numbered starting from 0 and incrementing by 1 by default. Given you've supplied a starting index, namely Administration = 1
, your enum is numbered as follows:
Administration = 1
Lawyers = 2
PropertyManagement = 3
Bookkeeping = 4
Secretariat = 5
So you can simply sort using the default sort for the collection, as explained in Sorting a List<int>.
Upvotes: 0
Reputation: 30062
Array.Sort()
uses the underlying type by default to compare the elements:
List<Group> groups = new List<Group>()
{
Group.Bookkeeping, Group.Administration, Group.Secretariat, Group.Administration
};
groups.Sort();
Upvotes: 4