Linq排序方式与Lambda排序方式比较以及OrderBy、ThenBy的使用
沿用之前某一篇文章的实体类与EF操作类代码。数据库中增加几条数据
Linq 的排序方式,下面例子是根据RoleId 升序,Name降序
EFContext<Member> efMemberContext = new EFContext<Member>();
var memberSet = efMemberContext.Set<Member>().Include("Role");
var memberList = from m in memberSet
orderby m.RoleId ascending, m.Name descending
select m;
foreach (Member item in memberList)
{
Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);
}
输出结果如下:
SQL Profiler如下:
同样的方式如果用Lambda排序,先猜想如下,
EFContext<Member> efMemberContext = new EFContext<Member>();
var memberSet = efMemberContext.Set<Member>().Include("Role");
var memberList = memberSet.OrderBy(m => m.RoleId).OrderByDescending(m => m.Name);
foreach (Member item in memberList)
{
Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);
}
运行程序发现与linq方式的不一致,
SQL Profile如下:
发现连续调用OrderBy或者OrderByDescending之后,以最后一个为准排序,这时ThenBy就派上了用场。
ThenBy是使用OrderBy或者OrderByDescending之后,再次对结果进行二次排序
EFContext<Member> efMemberContext = new EFContext<Member>();
var memberSet = efMemberContext.Set<Member>().Include("Role");
var memberList = memberSet.OrderBy(m => m.RoleId).ThenByDescending(m => m.Name);
foreach (Member item in memberList)
{
Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);
}
如果想数据库中多个列排序一致,可以先OrderBy(或者OrderByDescending)后ThenBy(或者ThenByDescending),也可以在OrderBy或者OrderByDescending直接指定多个属性,这样生成的SQL就是多个列的排序(排序一致asc/desc)
EFContext<Member> efMemberContext = new EFContext<Member>();
var memberSet = efMemberContext.Set<Member>().Include("Role");
var memberList = memberSet.OrderBy(m => new { m.RoleId, m.Name });
foreach (Member item in memberList)
{
Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);
}