Search code examples
c#arrayslistsortingnumerical

Sort a List<String[]> numerically


I have a List<string[]>. I add to it with list.Add(new string[] {a, b, c, d}), where d is a string of numbers.

I want to sort the list numerically by the number in the fourth element of the array. So far I've only found this:

list.Sort((s, t) => String.Compare(s[3], t[3]));

but this sorts alphabetically, so 10 gets in front of 2 etc.

Is there an equally simple way to sort it numerically?


Solution

  • If you use linq, you can do:

    list = list.OrderBy(x => int.Parse(x[3])).ToList();
    

    This will create a new list though and probably won't be as efficient as sorting the list directly.