Question

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?

Was it helpful?

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.

OTHER TIPS

What about this?

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

or (if the list is all numbers, and you want the result as numbers):

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

(excuse formatting, on mobile)

list.Sort((s, t) => System.Collections.Comparer.Default.Compare(Int32.Parse(s[3]), Int32.Parse(t[3])));

My suggestion is that you should really implement your own class with public members a,b,c and d. You should then implement IComparable<T> and write your simple comparison logic in CompareTo() method.

Yet another solution (I have not seen here) is to implement a delegate as a sorter

 // Split the string into individual number strings
 List<String> items  = wrongOrderBase.Split(DELIMITER).ToList<String>();
 items.Sort(delegate(String strA, String strB)
            {
                int intA = int.Parse(strA);
                int intB = int.Parse(strB);
                return intA.CompareTo(intB);
            });
  // Re-join back into one string
  String sortedListString = String.Join(DELIMITER.ToString(), items);

This way if you want to do any special case stuff you can implement it in the delegate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top