wil*_*ace 3 c# sorting string split list
任何人都可以请帮我排序以下字符串列表:
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]);
有任何想法吗?
谢谢,
JP
OrderBy并且ThenBy不要修改原始列表,它们只返回一个新列表(以a的形式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
Run Code Online (Sandbox Code Playgroud)
将数字存储在字符串中并尝试排序时,您会得到奇怪的结果.我建议您将代码更改为:
boardObjectList = boardObjectList.OrderBy(p => int.Parse(p.Split()[0]))
.ThenBy(p => int.Parse(p.Split()[1]))
.ToList();
Run Code Online (Sandbox Code Playgroud)
此方法在排序之前将字符串转换为整数.这样做的原因是字符串排序按字母顺序排序,导致像这样排序:
1
10
11
12
2
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2162 次 |
| 最近记录: |