I need to sort a list in order that seems unusual

Asked

Viewed 269 times

6

I have a query and want to sort this query by the attribute code. I did it as follows:

consulta.OrderBy(c => c.Codigo);

Result obtained:

1.01
1.A
14.04
14.11
22.01
3.04
30.01
4.01
40.02

Expected result:

1.01
1.A
3.04
4.01
14.04
14.11
22.01
30.01
40.02
  • That is to say string, right? You can ensure that always always in this format and will have at most two digits before decimal point?

3 answers

6


You can use PadLeft() to align the text, but you may need something more complex if the pattern is not so linear. It complicates a little more solving the alignment after the decimal point, so you’d have to find where it is.

using System.Collections.Generic;
using System.Linq;
using static System.Console;
                    
public class Program {
    public static void Main() {
        var lista = new List<string> { "1.01", "1.A", "14.04", "14.11", "22.01", "3.04", "30.01", "4.01", "40.02" };
        foreach (var item in lista.OrderBy(i => { var partes = i.Split('.'); return partes[0].PadLeft(2) + partes[1]; })) {
            WriteLine(item);
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

5

For this specific case I recommend you make a IComparer<T>.

public class MyStringComparer : IComparer<string>
{
     public int Compare(string x, string y){
        string[] xs = x.Split('.'), ys = y.Split('.');

        int x1, y1,
        comp;

        //assumi que antes do ponto sempre é um int então
        if(int.TryParse(xs[0], out x1) && int.TryParse(ys[0], out y1)){
            comp = x1.CompareTo(y1);

            return comp == 0 ? string.Compare(xs[1], ys[1]) : comp;
        }

        comp = string.Compare(xs[0], ys[0]);
        return comp == 0 ? string.Compare(xs[1], ys[1]) : comp;
    }
}

Here’s a example of it working :)

3

You will have to go through the string looking for the point for each record and then sort it with the initial code and then sort it again with the final code. A little boring to do and depending on it can consume a lot of processing, it may be easier to create two columns in the database (composite key) and remove the point.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.