I have number-text list and I want to create common custom comparer logic to sort this list(s) using C#. E.g.
var numericList = new List<string>{"100", "--", "-0.98", "N/A", "0.00", "-888"};
var stringList = new List<string> {"Smith", "--", "Peter", "", "Jim", "Ken", "NA"};
which contains some special characters like --, N/A,Space etc. And expected result after sort will be - For NemericList Ascending -> N/A, -- , -888 , -0.98 , 0.00 , 100 For StringList Ascending -> Jim, Ken, N/A, Peter, Smith, Empty, --
I created following custom comparer logic which does some level of sorting but not matching with the expected result. Please suggest me the way to achieve this.
public class NumberTextComparer : IComparer<string> { public int Compare(string s1, string s2) { double number1, number2; var isS1Numeric = double.TryParse(s1, out number1); var isS2Numeric = double.TryParse(s2, out number2); if (isS1Numeric && isS2Numeric) { if (number1 > number2) return 1; if (number1 < number2) return -1; return 0; } return isS1Numeric ? 1 : (isS2Numeric ? -1 : String.Compare(s1, s2, StringComparison.OrdinalIgnoreCase)); } }
var comparer = new NumberTextComparer();
var numericSortedListASC = numericList.OrderBy(str => str, comparer);
var stringSortedListASC = stringList.OrderBy(str => str, comparer);
Your code works correct. Se here. Results:
The problem is your assumption, that the "" and "--" come after letters. Since they have a lower position in the ascii-table they come first.
This would be a simple fix. Try here