1

So I have this numbered list that I need to sort numerically:

1
1.1.
1.1.1.
1.1.2.
1.1.3.
1.1.4.
1.1.5.
1.1.6.
1.1.7.
1.2.
1.2.1.
1.2.2.
1.2.3.
1.2.4.
1.2.5.
1.2.6.
1.3.
1.3.1.
1.3.2.
1.3.3.
1.3.4.
1.4.
1.4.1.
1.4.2.
1.4.3.
1.5.
1.5.1.
1.5.2.
1.5.3.
1.6.
1.6.1.
1.6.1.1.
1.6.1.2.
1.6.2.
1.6.2.1.
1.6.2.2.
1.6.2.3.
1.6.2.4.
1.6.2.5.
1.6.2.6.
1.6.3.
1.6.3.1.
1.6.3.2.
1.6.3.3.
1.6.3.4.
1.6.3.5.
1.6.4.
1.6.5.
1.7.
1.7.1.
1.7.1.1.
1.7.1.2.
1.7.1.3.
1.7.2.
1.7.3.
1.7.4.
1.7.5.
1.7.5.1.
1.7.5.2.
1.7.6.
1.7.7.
1.7.8.
1.7.9.
1.8.
1.9.
1.10.

Issue is when trying to sort 1.10. will come right before 1.2. instead of after 1.9.

Any Idea how I can achieve this using C# or linq?

Thanks.

2 Answers2

1

You can create an IComparer<T> class to help the sorter do what you want:

class MyComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        string[] xParts = x.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
        string[] yParts = y.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0;;i++)
        {
            if (xParts.Length >= i && yParts.Length < i)
                return 1;
            if (xParts.Length < i && yParts.Length >= i)
                return -1;
            if (xParts.Length < i && yParts.Length < i)
                return 0;

            int compared = int.Parse(xParts[i]).CompareTo(int.Parse(yParts[i]));
            if (compared != 0)
                return compared;
        }
    }
}

Then you can sort your values like so:

var sorted = values.OrderBy(s => s, new MyComparer()).ToList();
itsme86
  • 19,266
  • 4
  • 41
  • 57
-1

you can use Sort method of the List

 List<int> lista = new List<int>() {2,6,1,2,4,9,0,3};
                lista.Sort();

                foreach (var item in lista)
                {
                    Console.WriteLine(item);
                }

                Console.ReadKey();
Hairon Chaviano
  • 435
  • 2
  • 5
  • 1
    This doesn't address the issue in the question: There is a collection of strings in the form "1.10.1.", "1.2.1.", etc. OP knows how to perform a default sort. The question is how to make "1.10.1." sort ***after*** "1.2.1." – 15ee8f99-57ff-4f92-890c-b56153 Oct 09 '19 at 19:10