Can anyone please help me sort the following List of Strings:
The List<String> contains coordinates
[0] “0 0”
[1] “0 1”
[2] “0 2”
[3] “0 3”
[4] “1 1”
[5] “1 2”
[6] “1 3”
Although It may not always be in that order I would like to make sure it is, by sorting / ordering it (sort by X coordinate ASC then by Y coordinate ASC)
I have tried this but it does not alter the list at all? – see below
boardObjectList.OrderBy(p => (p.Split())[0]).ThenBy(p=> (p.Split())[1]);
Any ideas?
Thanks,
JP
OrderByandThenBydo not modify the original list, they only return a new list (in the form of anIEnumerable<>). What you need to do is create a newList<>from the resultingIEnumerable<>, like this:You will get strange results when storing numbers in strings, and trying to sort. I recommend changing your code to this:
This method converts the strings into integers before sorting. The reason to do this is that string sorting sorts alphabetically, leading to sorting like this: