我有一个List<string>
这样的人
List<string> Test_List = new List<string>()
{
"ZZA-KG-TEST",
"ZZA-EG-TEST",
"ZZA-KL-10A",
"ZZA-KL-5A",
"ZZA-KL-1A",
"ZZA-FG-TEST",
"RO-ELEVER"
};
排序后预期的输出
List<string> Test_List = new List<string>()
{
"ZZA-KL-1A",
"ZZA-KL-5A",
"ZZA-KL-10A",
"ZZA-KG-TEST",
"ZZA-FG-TEST",
"ZZA-EG-TEST",
"RO-ELEVER"
};
我实际上所得到的是
List<string> Test_List = new List<string>()
{
"ZZA-KL-1A",
"ZZA-KL-5A",
"ZZA-KL-10A",
"RO-ELEVER"
"ZZA-EG-TEST",
"ZZA-FG-TEST",
"ZZA-KG-TEST",
};
我的代码是这个
var data = Test_List
.OrderByDescending(i => i.Contains("-KL-"))
.ThenBy(i => i, new AlphanumericComparer())
.ThenByDescending(i => i.Contains("-KG-"))
.ThenBy(i => i, new AlphanumericComparer())
.ThenByDescending(i => i.Contains("-FG-"))
.ThenBy(i => i, new AlphanumericComparer())
.ThenByDescending(i => i.Contains("-EG-"))
.ThenBy(i => i, new AlphanumericComparer());
class AlphanumericComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
static extern int StrCmpLogicalW(string s1, string s2);
public int Compare(string x, string y) => StrCmpLogicalW(x, y);
}
有什么想法吗?
编辑,我需要所有包含-KL-
的项目都位于 top 处,然后使用-KL-
和-KG-
对其进行排序, -FG-
和-EG-
,然后其余的
答案 0 :(得分:4)
您可能想要首先订购组(按此顺序{KL, KG, FG, EG, all_the_rest
):
.OrderByDescending(i => i.Contains("-KL-"))
.ThenByDescending(i => i.Contains("-KG-"))
.ThenByDescending(i => i.Contains("-FG-"))
.ThenByDescending(i => i.Contains("-EG-"))
然后才在每个组中订购项目:
.ThenBy(i => i, new AlphanumericComparer());
即
var data = Test_List
.OrderByDescending(i => i.Contains("-KL-"))
.ThenByDescending(i => i.Contains("-KG-"))
.ThenByDescending(i => i.Contains("-FG-"))
.ThenByDescending(i => i.Contains("-EG-"))
.ThenBy(i => i, new AlphanumericComparer());