Linq Orderby null,string.Empty, 指定字符
点击查看代码
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var strL = new List<string>{"4", "2", null, "3", "1"};
Console.WriteLine("*********null**to the end*********");
Console.WriteLine(string.Join("-", strL.OrderBy(e => e is null ? 1 : 0)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e is null ? 1 : 0).ThenBy(e => e)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e is null ? 1 : 0).ThenByDescending(e => e)));
Console.WriteLine("*********null**to the start***********");
Console.WriteLine(string.Join("-", strL.OrderBy(e => e is null ? 0 : 1)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e is null ? 0 : 1).ThenBy(e => e)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e is null ? 0 : 1).ThenByDescending(e => e)));
Console.WriteLine("*********string.Empty**to the end***********");
strL = new List<string>{"4", "2", "", "3", "1"};
Console.WriteLine(string.Join("-", strL.OrderBy(e => e == string.Empty ? 1 : 0)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e == string.Empty ? 1 : 0).ThenBy(e => e)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e == string.Empty ? 1 : 0).ThenByDescending(e => e)));
Console.WriteLine("*********Specify Characters**to the end***********");
strL = new List<string>{"4", "2", "%", "3", "1"};
Console.WriteLine(string.Join("-", strL.OrderBy(e => e == "%" ? 1 : 0)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e == "%" ? 1 : 0).ThenBy(e => e)));
Console.WriteLine(string.Join("-", strL.OrderBy(e => e == "%" ? 1 : 0).ThenByDescending(e => e)));
}
}
输出:
*********null**to the end*********
4-2-3-1-
1-2-3-4-
4-3-2-1-
*********null**to the start***********
-4-2-3-1
-1-2-3-4
-4-3-2-1
*********string.Empty**to the end***********
4-2-3-1-
1-2-3-4-
4-3-2-1-
*********Specify Characters**to the end***********
4-2-3-1-%
1-2-3-4-%
4-3-2-1-%