C # sort list by Enum

I have an Entity list that has an enumeration.

public class Car { public int CarId { get; set; } public string CarName { get; set; } public CarCategory CarCategory { get; set; } } public enum CarCategory { None = 0, kLowRange = 1, kMidRange = 2, kHighRange = 3 } 

Now I have a list of cars, I would like to use Comparer and run it on an enumeration so that the whole object having a CarCategory like kMidRange and kHighRange will be sorted first in the list.

I tried with the answer, but havent found any luck.

Thanks.

UPDATE: I have a mistake that I am making. I looked at

 var sortedList = carList .OrderBy(x => x.CarCategory, new EnumComparer<CarCategory> { CarCategory.kMidRange, CarCategory.kHighRange}); 

But only the same values ​​were obtained. I have to add .ToList () to get the result.

 var sortedList = carList .OrderBy(x => x.CarCategory, new EnumComparer<CarCategory> { CarCategory.kMidRange, CarCategory.kHighRange}) .ToList(); 

Give me the expected results. To blame!

+5
source share
1 answer

enum is an effective integer ( int ) in your case

Approved types for listing are bytes, sbyte, short, ushort, int, uint, long, or ulong.

See https://msdn.microsoft.com/en-us/library/sbbt4032.aspx for more details.

Since the CarCategory implementation has the elements in the right order, you can only put

  var sortedList = carList .OrderByDescending(x => (int) (x.CarCategory)) .ToList(); 

please note Descending : you want kHighRange be on top. If you need an arbitrary order, for example.

 kMidRange, kHighRange, None, kLowRange 

I suggest using a mapping:

  // desired order: None should be 3d, LowRange 4th, MidRange 1st, HighRange 2nd int[] map = new[] {3, 4, 1, 2}; var sortedList = carList .OrderBy(x => map[(int) (x.CarCategory)]) .ToList(); 
+6
source

Source: https://habr.com/ru/post/1264931/


All Articles