C# linq到实体在concat之后跳过
我想先显示没有显示辅助ID的结果,然后显示有辅助ID的项目。但是我需要C# linq到实体在concat之后跳过,c#,entity-framework,linq,C#,Entity Framework,Linq,我想先显示没有显示辅助ID的结果,然后显示有辅助ID的项目。但是我需要跳过和获取 IQueryable<thing> result; IQueryable<thing> result2; result2 = result .Where(t => !(t.second_id == null || t.second_id.Trim() == string.Empty)) .OrderBy(t => t.second_id); result =
跳过和获取
IQueryable<thing> result;
IQueryable<thing> result2;
result2 = result
.Where(t => !(t.second_id == null || t.second_id.Trim() == string.Empty))
.OrderBy(t => t.second_id);
result = result
.Where(t => (t.second_id== null || t.second_id.Trim() == string.Empty))
.OrderBy(t => t.first_id);
result = result.Concat(result2);
return result
.Select(t => t.primary_key)
.Skip(pageSize * pageNumber)
.Take(pageSize)
.ToList();
IQueryable结果;
可测量结果2;
结果2=结果
.Where(t=>!(t.second_id==null | | t.second_id.Trim()==string.Empty))
.OrderBy(t=>t.second\u id);
结果=结果
其中(t=>(t.second_id==null | | t.second_id.Trim()==string.Empty))
.OrderBy(t=>t.first\u id);
结果=result.Concat(result2);
返回结果
.Select(t=>t.primary_键)
.跳过(页面大小*页码)
.Take(页面大小)
.ToList();
问题是在Concat
之后,IQueryable
不再是技术上的顺序,因此Skip
和Take
抛出错误。像这样:
只需一个查询即可完成此项工作
result = result
.OrderByDescending(t => (t.second_id== null || t.second_id.Trim() ==
string.Empty))
.ThenBy(t => t.second_id)
.ThenBy(t => t.first_id)
.Select(t => t.primary_key)
.Skip(pageSize * pageNumber)
.Take(pageSize)
.ToList();
可以使用条件运算符在一个查询中执行此操作:
return result.OrderBy(t => (t.second_id != null && t.second_id.Trim() != String.Empty))
.ThenBy(t => (t.second_id != null && t.second_id.Trim() != String.Empty) ? t.second_id : t.first_id)
.Select(t => t.primary_key)
.Skip(pageSize * pageNumber)
.Take(pageSize)
.ToList();
如果您需要以某种方式订购重复的second\u id
,则需要进行一些调整,但您的原始代码没有
PS我加入了否定运算符,因为我认为它读起来更清楚。你的问题是什么?为什么不能在最后一次Select()
调用之后简单地添加一个或多个OrderBy()
调用?另外,(t.second\u id==null | | t.second\u id.Trim()==string.Empty)
可以是string.IsNullOrWhiteSpace(t.second\u id)
@CamiloTerevinto我认为这不适用于实体framework@SamIam它可以翻译IsNullOrWhiteSpace
,就像它可以翻译Trim
。@CamiloTerevinto Samlam是对的。它不起作用。我已经试过了。如果second\u id
有多个不同长度的空格字符串,或者有空字符串和空字符串,我想你的第一个ThenBy
会有问题。@NetMage我用不同的字符串测试过它,包括空字符串和空字符串,它可以工作。毕竟,OrderBy只是遵循order键的IComparable实现中描述的模式,我相信字符串实现涵盖了所有情况。请尝试使用second\u id
=”和second\u id
=”(两个空格)进行测试在这种情况下,您将看到它们不是按first\u id
排序的,但它们应该是。@NetMage是的,您是对的。Null和string.Empty不相等,它将Null置于string.Empty之上。所以看起来他们没有被分类。我只测试了null或string.Empty。我认为字符串比较器将它们视为相等的。在一般情况下,它仍然可以工作,因为数据库中不太可能有空字符串作为键。总的来说,我会避免使用字符串键。