c# - 对包含坐标 x 和 y 的 List<String> 进行排序

标签 c# string list sorting split

谁能帮我对以下字符串列表进行排序:

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]);

有什么想法吗?

谢谢,
日语

最佳答案

OrderByThenBy不要修改原始列表,它们只会返回一个新列表(以 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/

相关文章:

c# - 自动显示 datagridview 中的更改

c# - 需要使用 angularjs 将隐藏的输入值发送到 mvc Controller

MySQL 使用旧值和新字符串更新 varchar 值

python - 返回元组列表中的唯一记录以及具有最大日期时间的非唯一记录

C#简单3D碰撞检测

c# - 如何在 Excel 中保留 Excel 功能区加载项的数据

c - 检查字符串卡住的函数

python - 在字符串列表 (Python) 中查找特定模式(正则表达式)

c++ - wxWidgets,wxListCtrl : How to prevent auto size of column when db-click on divider

java - 与JAVA中的ArrayList不同的值