我有一个要排序的列表:
List<string> temp = {
"Mina 1", "Mina 2",
"Planning 3", "Planning 2", "Planning 1", "Planning 4",
"Kira 2", "Kira 1"};要排序的列表:
// Sort items based on the following order of name
List<string> listToSort= {"Planning", "Mina", "Kira" };我正在尝试根据listToSort和数字增量对temp进行排序
预期结果:
List<string> temp = {
"Planning 1", "Planning 2", "Planning 3", "Planning 4",
"Mina 1", "Mina 2",
"Kira 1", "Kira 2"};发布于 2021-08-15 06:49:20
由于这些都是列表,因此可以组合使用FindIndex和StartsWith
var result = temp
.OrderBy(t => listToSort.FindIndex(s => s.StartsWith(t)))
.ThenBy(t => t);发布于 2021-08-15 06:58:17
虽然不是最有效的,但一种选择是使用SelectMany
var sorted = listToSort.SelectMany(sortKey => temp.Where(t => t.StartsWith(sortKey)).OrderBy(s => s));对于listToSort中的每个字符串,SelectMany都会查找temp中的所有相关字符串并按它们排序。
如果你需要自然排序(所以"Kira 11“会排在"Kira 9”之后),你可以添加一个比较器,例如Natural Sort Order in C#
https://stackoverflow.com/questions/68789292
复制相似问题