Conditionally adding .Take ()

I currently have this, which automatically takes up 500 lines:

var orderQuery = subsetTable.Where(pred).OrderByDescending(o => o.CreationDate).Take(500); 

I would like to make the Take () conditional conditional, something like this:

 var orderQuery = subsetTable.Where(pred).OrderByDescending(o => o.CreationDate); if (condition) orderQuery = orderQuery.Take(500); 

Is it possible?

Edit:
Compiler says

"It is not possible to implicitly convert the type 'System.Linq.IQueryable' to 'System.Linq.IOrderedQueryable."

+6
source share
4 answers

Add "AsQueryable" to create types:

 var orderQuery = subsetTable.Where(pred).OrderByDescending(o => o.CreationDate).AsQueryable(); if (condition) orderQuery = orderQuery.Take(500); 
+8
source

In Linq-to-Objects, var will be output to IOrderedEnumerable<T> , where T is the type of your object. Take() will give an IEnumerable<T> , so your line of code will not be allowed. (IOrderedEnumerable is more defined than IEnumerable, you need your query to be entered in a less defined way.) And, as the comments note, the same is true for providers who deal with IQueryable<T> terms, which themselves can be expressed as less specified IEnumerable<T> .

To do this, explicitly type your query into the smaller specified type that you need, IEnumerable<T> or IQueryable<T> , and then you can apply your conditional Take .

 IEnumerable<YourType> orderedQuery = ... if (condition) orderedQuery = orderedQuery.Take(n); 
+10
source

Is it possible?

Yes. Your code should work almost as written. You just need to eliminate var . Assuming your type is Order . you should use:

 IQueryable<Order> orderQuery = subsetTable.Where(pred).OrderByDescending(o => o.CreationDate); if (condition) orderQuery = orderQuery.Take(500); 
+6
source

What I do is add Sort at the end to avoid having to convert them.

 var orderQuery = subsetTable.Where(pred); if (condition) orderQuery = orderQuery.Take(500); orderQuery = orderQuery.OrderByDescending(o => o.CreationDate); 
-1
source

Source: https://habr.com/ru/post/943573/


All Articles