假设我有这个清单:
List<string> somelist = new List<string>();
somelist.Add("a");
somelist.Add("b");
somelist.Add("b");
somelist.Add("a*");
somelist.Add("b");
somelist.Add("a*");
somelist.Add("a");
然后订购:
somelist = somelist.OrderBy(x => x).ToList();
当我使用OrderBy时,我的订购方式如下:
a
a
a*
a*
b
b
b
但我想要&#34; *&#34;成为第一 我该怎么办?
答案 0 :(得分:2)
您可以使用:
somelist = somelist
.OrderBy(x => x.TrimEnd('*')) // remove * to keep alphabetical order
.ThenByDescending(x => x.EndsWith("*")) // bool(true=1, false=0), ends with * first
.ToList();
假设不仅a*
而且(如果可能的话)b*
应该首先出现。
这保持了自然顺序,因此如果有"b*"
,它将属于"b"
- 组。如果您希望所有以*
开头的结尾,无论首字母是什么:
somelist = somelist
.OrderByDescending(x => x.EndsWith("*"))
.ThenBy(x => x)
.ToList();
答案 1 :(得分:0)
这样你可以&#34;命令&#34;所有符号不仅仅是&#34; *&#34;
List<string> somelist = new List<string>();
...... // INIT VALUES
var ordered = somelist .Sort((x, y) =>
{
if(Char.IsLetterOrDigit(x[0])){
if(!Char.IsLetterOrDigit(y[0])){
// x is a letter/digit and y is not, override regular CompareTo
return -1;
}
}
else if (Char.IsLetterOrDigit(y[0]))
{
// y is a letter/digit and x is not, override regular CompareTo
return 1;
}
return x.CompareTo(y);
}).ToList();