如何在此特定场景中执行有效的Order By
本文关键字:执行 有效 By Order | 更新日期: 2023-09-27 18:17:36
所以我写这个查询,它工作得很好:
(from schools in context.Schools
// some kind of fancy joins
select new SomeLocalDTO()
{
SchoolId = schools.SchoolId,
FancySchoolName = schools.SchoolId + "**** -***** " + schools.SchoolName
})
.AsQueryable();
/// I have some fancy code here which will aslso take care of take/skip.
// I WANT TO DO ORDER BY HERE, after the skip and take
问题是我想在完成所有花哨的代码后进行排序/跳过。但问题是我没有学校名称在选择语句,而是我有什么是fanyschoolname。我该怎么办?
注1:我不能改变someelocaldto,以在select中包含schoolname。
注2:根据我的业务需求,我不关心我从ABCDEF得到的结果是ABC还是FED。注3:我知道这是一个奇怪的要求,只是这是一个奇怪的业务要求。
你可以创建一个SomeLocalDTO
的子类,它确实包括SchoolName
,让你的LINQ创建这些对象,然后当你返回到调用者时,只是向下cast到SomeLocalDTO
。
更新:
根据你所说的一切,我仍然是这样理解你想要什么…在初始查询之后的order/Take/Skip,但仍按SchoolName
排序:
public class MyDTO: SomeLocalDTO
{
public string SchoolName {get;set;}
}
var result = (from schools in context.Schools
// some kind of fancy joins
select new MyDTO()
{
SchoolId = schools.SchoolId,
FancySchoolName = schools.SchoolId + "**** -***** " + schools.SchoolName,
SchoolName = schools.SchoolName
});
return result.OrderBy(s => s.SchoolName)
.Skip(...)
.Take(...)
.Cast<SomeLocalDTO>();
这是一个非常奇怪的请求来排序,做/跳过,然后是不同的排序,但是:
var something=(from schools in context.Schools
// some kind of fancy joins
orderby schools.Name
select schools);
// take/skip
var result=something.OrderBy(...).Select(schools=>
new SomeLocalDTO()
{
SchoolId = schools.SchoolId,
FancySchoolName = schools.SchoolId + "**** -***** " + schools.SchoolName
});
根据你的困惑,我怀疑这就是你想要的:
var something=context.Schools
.OrderBy(schools=>schools.SchoolName)
.Skip(...)
.Take(...)
.Select(schools=>
new SomeLocalDTO()
{
SchoolId = schools.SchoolId,
FancySchoolName = schools.SchoolId + "**** -***** " + schools.SchoolName
});