其他分享
首页 > 其他分享> > 排序用法

排序用法

作者:互联网

1.基础排序

 var list = db.Queryable<Student>().OrderBy("StudentId DESC").ToList();

//SELECT `StudentId`,`Name`,`SchoolId` FROM `Student` ORDER BY StudentId DESC

2.表达式排序

var list = db.Queryable<Student, School>((st, sc) => new JoinQueryInfos(JoinType.Left, st.SchoolId == sc.SchoolId))
    .OrderBy(st => st.StudentId)
    .OrderBy((st, sc) => sc.SchoolId, OrderByType.Desc)
    .Select<ViewModelStudent>().ToList();
    
//SELECT st.`StudentId` AS `StudentId`,st.`Name` AS `Name`,st.`SchoolId` AS `SchoolId`,sc.`SchoolName` AS `SchoolName` FROM `Student` st
   Left JOIN `School` sc ON( `st`.`SchoolId` = `sc`.`SchoolId` )  
   ORDER BY `st`.`StudentId` ASC,`sc`.`SchoolId` DESC

Student和School结合的实体类
ViewModelStudent表中的数据

3.表达式连写

3.1 升序

var list = db.Queryable<Student>().OrderBy(it => new { it.StudentId,it.SchoolId }).ToList();

//SELECT `StudentId`,`Name`,`SchoolId` FROM `Student` ORDER BY `StudentId` ASC,`SchoolId` ASC

3.2 降序

var list = db.Queryable<Student>().OrderBy(it=>new { it.StudentId,SchoolId = SqlFunc.Desc(it.SchoolId)}).ToList();

//SELECT `StudentId`,`Name`,`SchoolId` FROM `Student` ORDER BY `StudentId`,`SchoolId` DESC

4.随机排序取10条

var list = db.Queryable<Student().OrderBy(it=>SqlFunc.GetRandom()).Take(3).ToList();

//SELECT `StudentId`,`Name`,`SchoolId` FROM `Student`    ORDER BY rand() ASC LIMIT 0,3

SqlFunc.GetRandom:随机数函数,不理解的可以用下面语句测试查看

select *,rand() as random from student  order by random

5.OrderByIF

//当条件IsOrderBy == true,OrderBy才生效
OrderByIF(IsOrderBy, it=>it.Id) 

文档参考:排序用法

标签:OrderBy,SchoolId,Name,st,StudentId,用法,sc,排序
来源: https://www.cnblogs.com/DotNeter-Hpf/p/16619620.html