Comparing Enum Sort Values

In the project, I have an external enumeration (generated from a service link). Therefore, I cannot change the values ​​of the enumeration.

How can I effectively compare these enum values ​​with each other?

Here is a listing example

public enum Values { A, B, C, D, E, F, G, H } 

And the sort order I want them is not the same (something like F, H, A, C, B, ...)

Now I have an extension method with some comparisons. (with another listing with the order I want)

 public static int CompareTo(this Values x, Values y) { var orderedX = GetOrderedValues(x); var orderedY = GetOrderedValues(y); return orderedX.CompareTo(orderedY); } internal enum ValuesOrdered { F = 0, H = 1, C = 2, D = 3, B = 4, A = 5, E = 6, G = 7 } internal static ValuesOrdered GetOrderedValues(this Values x) { switch (x) { case Values.A: { return ValuesOrdered.A; } // and so on... } } 

Could this be achieved more efficiently?

+4
source share
3 answers

If all you want to do is CompareTo , then I think you could simplify this with a dictionary:

 static Dictionary<Values, int> order = new Dictionary<Values, int> { {Values.A, 3}, {Values.B, 5}, {Values.C, 4}, {Values.D, 6}, {Values.E, 8}, {Values.F, 1}, {Values.G, 7}, {Values.H, 2} }; public static int CompareTo(this Values x, Values y) { return order[x].CompareTo(order[y]); } 

However , I'm not sure why you need to implement an extension method called CompareTo, but I hope you do not expect it to override Enum.CompareTo . For instance,

 var values = Enum.GetValues(typeof(Values)).Cast<Values>().ToArray(); Array.Sort(values); Console.WriteLine(string.Join(" ", values)); //OUTPUT: ABCDEFGH 
+2
source

I believe that the simplest would be to implement your comparison function this way:

 public static int CompareTo(this Values x, Values y) { var sortOrder = new[] { Values.F, Values.H, Values.C, Values.D, Values.B, Values.A, Values.E, Values.G }; return Array.IndexOf(sortOrder, x) - Array.IndexOf(sortOrder, y); } 

Of course, you will want to move the sortOrder initialization outside the function so that it sortOrder only once.

Regarding the choice of an array as a data structure that encodes the desired ordering: this is not only the simplest, but for such a small number of elements, a linear search is probably also the fastest.

+4
source

instead, list ValuesOrdered using static readonly SortedList (you cannot use the constant for SortedList) as follows:

 private static readonly SortedList<Values, int> ordered = new SortedList<Values, int> { {Values.F,0}, {Values.H,1}, {Values.C,2}, {Values.D,3}, {Values.B,4}, {Values.A,5}, {Values.E,6}, {Values.G,7}, }; 

And the "CompareTo" method will look like this:

 public static int CompareTo(this Values x, Values y) { return Comparer<int>.Default.Compare(ordered[x], ordered[y]); } 

Enjoy !:-)

+2
source

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


All Articles