2

I have a list of <string[]>.
Added items would look like this

list.Add(new string[]{"1", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"2a", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"2", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"3a", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"3b", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"4", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"5", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"10", "A", "333", "666", "16.02.2013 03:00"});
list.Add(new string[]{"11", "A", "333", "666", "16.02.2013 03:00"});

After parsing data from file and adding them to List I have to show all data in DataGridView, and after adding all data to DataGridView I want to make user to able sort it by clicking on column header.

Problem is that if user will want to sort rows by first column it will sort like this

1   A   333 666 16.02.2013 03:00
10  A   333 666 16.02.2013 03:00
11  A   333 666 16.02.2013 03:00
2   A   333 666 16.02.2013 03:00
2a  A   333 666 16.02.2013 03:00
3a  A   333 666 16.02.2013 03:00
3b  A   333 666 16.02.2013 03:00
4   A   333 666 16.02.2013 03:00
5   A   333 666 16.02.2013 03:00

but correct way would be this:

1   A   333 666 16.02.2013 03:00
2   A   333 666 16.02.2013 03:00
2a  A   333 666 16.02.2013 03:00
3a  A   333 666 16.02.2013 03:00
3b  A   333 666 16.02.2013 03:00
4   A   333 666 16.02.2013 03:00
5   A   333 666 16.02.2013 03:00
10  A   333 666 16.02.2013 03:00
11  A   333 666 16.02.2013 03:00

How can I sort List of string arrays by specific index of array using natural sort?
I can't use LINQ

spajce
  • 7,044
  • 5
  • 29
  • 44
user1527484
  • 67
  • 3
  • 9

1 Answers1

1

You're looking for a natural sort. There are many implementations around the web; I'd just choose one of those and copy it into your project.

Now, since you want to sort in a DataGridView, you'll need to attach to the SortCompare event and do your custom sorting there. It'll look something like this:

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    // Since you want a natural sort in the first column
    if (e.Column.Index == 0)
    {
        // Create an instance of your natural sort comparer here
        IComparer<string> comparer = new YourNaturalComparer()

        // Perform the sort
        e.SortResult = comparer.Compare(
            e.CellValue1.ToString(), e.CellValue2.ToString());

        // Signal that we handled the sorting for this column
        e.Handled = true;
    }
}
Community
  • 1
  • 1
Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88