LINQ OrderBy & ThenBy
🏷️ C#
OrderBy
如果多次使用时,后面的会覆盖前面的排序(Queryable.OrderBy Method)。
The expected behavior is that it sorts the elements of
source
based on the key obtained by invokingkeySelector
on each element ofsource
. Thecomparer
parameter is used to compare keys.
如果想实现多级排序需要使用 ThenBy
方法(=> Queryable.ThenBy Method)。
The expected behavior is that it performs a secondary sort of the elements of
source
based on the key obtained by invokingkeySelector
on each element ofsource
. All previously established sort orders are preserved. Thecomparer
parameter is used to compare key values.
可见 ThenBy
会保留之前的排序,而 OrderBy
不会。
网上看到的很多示例代码都是只有一个 ThenBy
的调用。下面是一段代码,测试在多个 ThenBy
同时使用时,是否能保留之前的排序。
根据打印结果,多个 ThenBy
同时使用时可以保留之前所有的排序的。
csharp
using Newtonsoft.Json;
using System;
using System.Linq;
namespace LinqOrderBy
{
class Program
{
static void Main(string[] args)
{
User[] users = {
new User() { Sex = 2, Age = 21, Point = 59 },
new User() { Sex = 2, Age = 21, Point = 60 },
new User() { Sex = 1, Age = 20, Point = 60 },
new User() { Sex = 2, Age = 19, Point = 59 },
new User() { Sex = 1, Age = 21, Point = 59 },
new User() { Sex = 1, Age = 19, Point = 61 },
new User() { Sex = 1, Age = 19, Point = 60 },
new User() { Sex = 2, Age = 19, Point = 60 },
new User() { Sex = 2, Age = 19, Point = 61 },
new User() { Sex = 2, Age = 20, Point = 59 },
new User() { Sex = 1, Age = 21, Point = 60 },
new User() { Sex = 1, Age = 20, Point = 61 },
new User() { Sex = 2, Age = 21, Point = 61 },
new User() { Sex = 1, Age = 20, Point = 59 },
new User() { Sex = 1, Age = 19, Point = 59 },
new User() { Sex = 1, Age = 21, Point = 61 },
new User() { Sex = 2, Age = 20, Point = 60 },
new User() { Sex = 2, Age = 20, Point = 61 },
};
var sortedUsers = users
.OrderBy(u => u.Sex)
.ThenBy(u => u.Age)
.ThenBy(u => u.Point)
.ToList();
foreach (var user in sortedUsers)
{
Console.WriteLine(JsonConvert.SerializeObject(user));
}
Console.ReadLine();
}
}
class User
{
public int Sex { get; set; }
public int Age { get; set; }
public int Point { get; set; }
}
}
打印结果:
json
{"Sex":1,"Age":19,"Point":59}
{"Sex":1,"Age":19,"Point":60}
{"Sex":1,"Age":19,"Point":61}
{"Sex":1,"Age":20,"Point":59}
{"Sex":1,"Age":20,"Point":60}
{"Sex":1,"Age":20,"Point":61}
{"Sex":1,"Age":21,"Point":59}
{"Sex":1,"Age":21,"Point":60}
{"Sex":1,"Age":21,"Point":61}
{"Sex":2,"Age":19,"Point":59}
{"Sex":2,"Age":19,"Point":60}
{"Sex":2,"Age":19,"Point":61}
{"Sex":2,"Age":20,"Point":59}
{"Sex":2,"Age":20,"Point":60}
{"Sex":2,"Age":20,"Point":61}
{"Sex":2,"Age":21,"Point":59}
{"Sex":2,"Age":21,"Point":60}
{"Sex":2,"Age":21,"Point":61}