谁能帮我对以下字符串列表进行排序:
List<String>包含坐标
[0]“0 0”
[1] "0 1"
[2] "0 2"
[3] "0 3"
[4] "1 1"
[5] "1 2"
[6] "1 3"
虽然它可能并不总是按该顺序排列,但我想通过对其进行排序/排序(按 X 坐标 ASC 排序,然后按 Y 坐标 ASC 排序)来确保它是这样
我试过了,但它根本没有改变列表? - 见下文
boardObjectList.OrderBy(p => (p.Split())[0]).ThenBy(p=> (p.Split())[1]);
有什么想法吗?
谢谢,
日语
最佳答案
OrderBy
和 ThenBy
不要修改原始列表,它们只会返回一个新列表(以 IEnumerable<>
的形式)。您需要做的是创建一个新的 List<>
来自结果 IEnumerable<>
,像这样:
// Note that we are assigning the variable to a new list
boardObjectList = boardObjectList.OrderBy(p => (p.Split())[0])
.ThenBy(p => (p.Split())[1])
.ToList(); // Also note that we call ToList,
// to get a List from an IEnumerable
在字符串中存储数字并尝试排序时,您会得到奇怪的结果。我建议将您的代码更改为:
boardObjectList = boardObjectList.OrderBy(p => int.Parse(p.Split()[0]))
.ThenBy(p => int.Parse(p.Split()[1]))
.ToList();
此方法在排序前将字符串转换为整数。这样做的原因是字符串排序是按字母顺序排序的,导致这样排序:
1
10
11
12
2
3
4
5
6
7
8
9
关于c# - 对包含坐标 x 和 y 的 List<String> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11915002/