[英]How can I tell if an IQueryable is an IOrderedQueryable?
I have an IQueryable. 我有一个IQueryable。 I have not called OrderBy on it or otherwise done anything with it. 我没有在它上面调用OrderBy或者用它做任何事情。
If I do: 如果我做:
// for some reason, isItOrdered is always true
var isItOrdered = myQueryable is IOrderedQueryable<T>
Why is this always true? 为什么这总是如此? (It seems like it shouldn't be.) And, more importantly, how can I tell if an IQueryable already has been ordered? (好像不应该这样。)更重要的是,如何判断IQueryable是否已被订购? (ie is truly an IOrderedQueryable) (即真正的IOrderedQueryable)
I would like to be able to do something like: 我希望能够做到这样的事情:
if (myQueryable is IOrderedQueryable<T>)
myQueryable = myQueryable.ThenBy(...);
else
myQueryable = myQueryable.OrderBy(...);
You haven't shown what's creating your queryable to start with, but perhaps it's naturally ordered in some way? 你还没有展示创建你的可查询的内容,但也许它以某种方式自然地排序?
What you've got does check whether it's really an IOrderedQueryable<T>
- I suspect that it's just that your query provider always provides an ordered queryable, even if the order isn't obvious. 你所得到的是检查它是否真的是一个IOrderedQueryable<T>
- 我怀疑它只是你的查询提供者总是提供一个有序的可查询,即使顺序不明显。
EDIT: Okay, something else you might try: 编辑:好的,你可能会尝试其他的东西:
if (typeof(IOrderedQueryable<T>).IsAssignableFrom(myQueryable.Expression.Type))
... or in general, print out myQueryable.Expression.Type
and see what it looks like. ...或者通常,打印出myQueryable.Expression.Type
并查看它的外观。
This seems to work 这似乎有效
if (query.Expression.Type == typeof(IOrderedQueryable<T>))
myQueryable = myQueryable.ThenBy(...);
else
myQueryable = myQueryable.OrderBy(...);
Some IQueryable
implementations reuse the same class for IOrderedQueryable<T>
. 一些IQueryable
实现为IOrderedQueryable<T>
重用相同的类。
There isn't much of a point in checking if it's really already ordered unless you know how it's ordered, otherwise you might order by the exact same property when you call ThenBy()
. 除非您知道它是如何订购的,否则检查它是否真的已经订购并没有多大意义,否则当您调用ThenBy()
时,您可能会使用完全相同的属性进行排序。
Also, you can't call Queryable.ThenBy()
on myQueryable
if it's a reference to IQueryable
—you have to cast it first: 另外,你不能在myQueryable
上调用Queryable.ThenBy()
,如果它是对IQueryable
的引用 - 你必须先抛出它:
if (myQueryable is IOrderedQueryable<T>)
myQueryable = ((IOrderedQueryable<T>) myQueryable).ThenBy(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.