Sort list by a string property with number

Asked

Viewed 1,039 times

2

I have an object of the type Ata where I own the property NroAta which corresponds to the number of the minutes in question, but in grid when I 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 method OrderBy.

  • 1

    You are not sorting numbers, you are sorting strings(text)

1 answer

5


Can you guarantee that it’s all valid number? You can do this:

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

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

Ideally it would be that a field that clearly needs to have numbers is numerical, then it would be simple.

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

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

  • I don’t know if I can guarantee they’ll always be valid numbers, I’ll have to check. But your answer already helped me, both in Convert for Int and Padleft, I hadn’t thought about it.

  • 1

    If you cannot guarantee, you will have to see what you can have and decide how to normalize the data, the PadLeft() can solve most situations.

Browser other questions tagged

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