LINQ 按字母顺序排序,后跟空字符串
本文关键字:字符串 排序 顺序 LINQ | 更新日期: 2023-09-27 18:31:16
我有一个字符串集合:
"", "c", "a", "b".
我想使用 LINQ orderby
以便顺序按字母顺序排列,但最后是空字符串。因此,在上面的例子中,顺序将是:
"a", "b", "c", ""
你可以使用类似的东西:
var result = new[] { "a", "c", "", "b", "d", }
.OrderBy(string.IsNullOrWhiteSpace)
.ThenBy(s => s);
//Outputs "a", "b", "c", "d", ""
除了现有的答案,您可以提供对OrderBy
重载的IComparer<string>
:
class Program
{
static void Main(string[] args)
{
var letters = new[] {"b", "a", "", "c", null, null, ""};
var ordered = letters.OrderBy(l => l, new NullOrEmptyStringReducer());
// Results: "a", "b", "c", "", "", null, null
Console.Read();
}
}
class NullOrEmptyStringReducer : IComparer<string>
{
public int Compare(string x, string y)
{
var xNull = x == null;
var yNull = y == null;
if (xNull && yNull)
return 0;
if (xNull)
return 1;
if (yNull)
return -1;
var xEmpty = x == "";
var yEmpty = y == "";
if (xEmpty && yEmpty)
return 0;
if (xEmpty)
return 1;
if (yEmpty)
return -1;
return string.Compare(x, y);
}
}
我并没有说这是IComparer
实现的一个很好的例子(如果两个字符串都为空,它可能需要执行空检查和处理),但答案的重点是演示OrderBy
重载,至少适用于问题的示例数据。
由于评论中的反馈和我自己的好奇心,我提供了一个稍微复杂的实现,它还负责对空字符串和空字符串相对排序。不处理空格。
不过,关键是提供IComparer<string>
的能力,而不是你选择写得有多好:-)
string[] linqSort = { "", "c","x", "a","" ,"b","z" };
var result = from s in linqSort
orderby string.IsNullOrEmpty(s),s
select s;