0

Having some problem on sorting in C#

I try to do

 string[] tempseq = ["0:0","0:5","0:10","0:1","0:6","0:11","0:2","0:7","0:12","0:3","0:8","0:13"]
 Array.Sort(tempseq);

The result come out as :

0:0 , 0:1 , 0:10 , 0:11 , 0:12 , 0:13 , 0:2 , 0:3 ,  0:5 , 0:6 , 0:7 , 0:8

How to sort it using the value after ":" ?

cikkidess
  • 13
  • 2
  • Should each value be enclosed in quotes? e.g. `"0:0"`? – Johnathan Barclay Jun 30 '21 at 10:41
  • If you are looking for ["Natural Sort"](https://www.bing.com/search?q=natural%20sort%20c%23&qs=n&form=QBRE&sp=-1&pq=natural%20sort%20c%23&sc=1-15&sk=&cvid=3ACA695A4CDA472A9B32CE0D3F224B42) then we have a duplicate here https://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp – Steve Jun 30 '21 at 10:44
  • Edit the array input – cikkidess Jun 30 '21 at 10:46

3 Answers3

0

you can sort with a compare function passed to sort, you just need to extract the part of the string you want to sort by

    string[] tempseq = { "0:0", "0:5", "0:10", "0:1",
         "0:6", "0:11", "0:2", "0:7", "0:12", "0:3", "0:8", "0:13" 
    };
    Func<string, int> second = (s) => int.Parse(s.Split(":")[1]);
    Array.Sort(tempseq, (l,r) => second(l).CompareTo(second(r)) );

for using first then second you could do

    (int, int) pair(string s)
    {
        var parts = s.Split(":").Select(int.Parse).ToArray();
        return (parts[0], parts[1]);
    };
    Array.Sort(tempseq, (l,r) =>
    {
        var left = pair(l);
        var right = pair(r);
        return left.Item1 == right.Item1 ? 
            left.Item2.CompareTo(right.Item2) : 
            left.Item1.CompareTo(right.Item1);
    });
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • just a quick understanding, what if i have "0:0", "0:5", "1:10", "1:1", "0:6", "0:11", "0:2", "0:7", "0:12", "0:3", "0:8", "0:13" and need to be sort it out and those have 1 in front need to be at back.. Are we able to compare it? – cikkidess Jul 07 '21 at 02:29
  • Its works well.. can know the what we terms for this? – cikkidess Jul 07 '21 at 05:44
0

Substring returns a new temporary string which needs to be garbage collected. The cost can add up quickly in a busy web application. This can be avoided by using ReadOnlySpanc.Slice instead of Substring

Array.Sort(tempseq,(a, b) => 
    int.Parse(a.AsSpan().Slice(a.IndexOf(':') + 1))
       .CompareTo(int.Parse(b.AsSpan().Slice(b.IndexOf(':') + 1))));

AsSpan creates a "read-only view" over a string's data instead of extracting a copy of the data

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
-1

It is rather simple to do just this:

string[] tempseq = new[] { "0:0", "0:5", "0:10", "0:1", "0:6", "0:11", "0:2", "0:7", "0:12", "0:3", "0:8", "0:13" };

string[] sorted = tempseq.OrderBy(x => int.Parse(x.Split(':')[1])).ToArray();

I then get this:

0:0 
0:1 
0:2 
0:3 
0:5 
0:6 
0:7 
0:8 
0:10 
0:11 
0:12 
0:13 
Enigmativity
  • 113,464
  • 11
  • 89
  • 172