I need to sort a list in order that seems incoum

6

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

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
    
asked by anonymous 19.12.2016 / 20:34

3 answers

6

You can use PadLeft() to align the text , but may need something more complex if the pattern is not so linear. It's a bit more complicated to resolve the alignment after the decimal point, so you would 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);
        }
    }
}

See running on dotNetFiddle and on CodingGround .

    
19.12.2016 / 20:49
4

For this particular 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 :)

    
19.12.2016 / 21:21
2

You'll have to go through the string by looking for the point at each record and then sort it with the initial code and then sort it again with the final code. A little annoying to do and, depending on it, can be very time-consuming, maybe it's easier to create two columns in the database (compound key) and remove the point.

    
19.12.2016 / 20:48