Alpha Digital Sort in C #

I have CSV data:

Number Version
1; AA .1
1; A01.1
1; A01.2
1; Z.7

Here I need to sort the Version column as shown below:

Number Version
1; AA .1
1; Z.7
1; A01.2
1; A01.1

So, if you see, the Z.7 entry should appear after AA.1. basically descending sorting should be done as follows:

Sorted Version:

BB
AA
Z
C
B
A

I have already tried the Alphabetical algorithm discussed at http://www.DaveKoelle.com Natural Sorter http://www.codeproject.com/Articles/22517/Natural-Sort-Comparer . It does everything I want except the sorting mentioned above.

+4
source share
1 answer

So, it looks like you need to sort some user logic, as shown in the CSV file. To do this, you must implement IComparer<string> in the class and implement the Compare method based on your requirement. It looks like in your case you need to first split the string into two parts, the alphabets part and the numeric part (using the regular expression), then first compare the string if they are the same, then compare the numeric part and return the value accordingly.

Then you can use this Comparer class to sort.

Update

Code example

 public class CustomStringComparer : IComparer<string> { public int Compare(string x, string y) { int? result; if (AnyParamIsNull(x, y, out result)) { return result.Value; } string x1, y1; double x2, y2; SplitInput(x, out x1, out x2); SplitInput(y, out y1, out y2); if (x1.Length == y1.Length) { result = string.Compare(x1, y1); if (result.Value == 0) { if (x2 < y2) { return -1; } else if (x2 > y2) { return 1; } else { return 0; } } else { return result.Value; } } else { //To make AA before Z when desending return x1.Length - y1.Length; } } private bool SplitInput(string input, out string alphabets, out double number) { Regex regex = new Regex(@"\d*[.]?\d+"); Match match = regex.Match(input); if (match.Success) { number = double.Parse(match.Value, CultureInfo.InvariantCulture); alphabets = input.Replace(match.Value, ""); return true; } else { throw new ArgumentException("Input string is not of correct format", input); } } private bool AnyParamIsNull(string x, string y, out int? result) { result = null; if (x == null) { if (y == null) { // If x is null and y is null, they're // equal. result = 0; return true; } else { // If x is null and y is not null, y // is greater. result = -1; return true; } } else { // If x is not null... // if (y == null) // ...and y is null, x is greater. { result = 1; return true; } } return false; } } 

To use this Comparer

  List<string> input = new List<string>() { "AA.1", "A01.1", "A01.2", "Z.7" }; input.Sort(new CustomStringComparer()); //To sort decending input.Reverse(); 

Caution: I have proven that the code above is correct and not otherwise. There may be some cross cases where it may not work as expected

+3
source

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


All Articles