Sort list by string property with number

2

I have an object of type Ata where I have the property NroAta that corresponds to the number of the Minutes in question, but in the grid when I will sort by this number, it ends up putting the numbers in the wrong order. Ex.:

1, 10, 12, 2, 23, 3 ... and so it goes.

I created a pseudo code of what I'm using to use as an example:

List<Ata> lstAtas = new List<Ata>()
            {
                new Ata{ NroAta = "1"},
                new Ata{ NroAta = "10"},
                new Ata{ NroAta = "6"},
                new Ata{ NroAta = "4"},
                new Ata{ NroAta = "5"},
                new Ata{ NroAta = "2"},
                new Ata{ NroAta = "3"},
            };

            lstAtas = lstAtas.OrderBy(x => x.NroAta).ToList();

            foreach (var ata in lstAtas)
            {
                Console.WriteLine("{0}", ata.NroAta);
            }

In the example, I need the numbers to be in the correct order: 1, 2, 3, 4, 5, 6, 10 using the OrderBy method.

    
asked by anonymous 09.09.2016 / 20:53

1 answer

5

Can you ensure that it's all valid number? You can do this:

lstAtas = lstAtas.OrderBy(x => Convert.ToInt32(x.NroAta)).ToList();

See working on dotNetFiddle .

Ideally, a field that clearly needs to have numbers would be numeric, that would be simple.

If you keep as text you have to use some trick. Others can be applied or converted to number or by manipulating the text to normalize it, using PadLeft() for example, so all texts could be the same size and this is important for sorting texts, since sorting of this type is positional.

If you are comparing two large or many small texts of different size between them, doing padding will generate another object since C # uses strings immutable may be inefficient. To optimize it would be interesting to create a comparison method in reverse starting at the end. This helps by avoiding copying the data and pressing the GC. Too bad that doing so can not use pointer to scan the array of characters since it is private. The gain will be limited because of this. You would need to test whether to use reflection at least if strings are large.

    
09.09.2016 / 20:57