开发者

use of .ToList().AsQueryable()

I came across linq query which ends in (...).ToList().AsQueryable(). I know the use of .ToList() and .AsQueryable() separately. But, what is the outcome if both are combined? When do we need to combine them? I hope this question is not too dump question. Thanks in advance.

First query:

Dim costAmounts = (From t In model.OrderTrades                            
Join o In model.Orders On t.OrdNum Equals o.OrdNum 
Where o.ClientCode = clientNumber And o.BookDate = sysrec.ETicketsBookDate
Group t By t.Buy, t.OrdNum Into Amount = Sum(t.BuyAmount) _
Select OrdNum = OrdNum, Currency = Buy, SellAmount = Amount).ToList().AsQueryable()

Second Query:

 Dim orders = (From a In costAmounts _
                    Group Join s In settlements On s.Currency Equals a.Currency _
                        And s.OrdNum Eq开发者_如何学Cuals a.OrdNum Into amounts = Group _
                    From g In amounts.DefaultIfEmpty _
                    Where g Is Nothing OrElse a.SellAmount - g.Paid <> 0 _
                    Select OrdNum = a.OrdNum Distinct).ToList()


You should never need to combine the two.

AsQueryable is there to give you lazy evaluation features, which the ToList completely negates.

So, the LINQ query is forced to be evaluated by ToList, then, the in memory list is converted to an IQueryable in order to allow... querying over it. Instead of constructing the query and only getting the results as needed.


The .ToList() would break the delayed execution which is often very helpful (passing queryables around will defer the execution, but could end up actually doing several executions later instead, if passed to multiple classes or methods). Once you do .AsQueryable() you then return the result as Queryable which might be a requirement.

EDIT: If we can agree that calling .ToList() on a queryable, and then pass the list around is the right pattern for some uses (i can really speed up your application in cases where your queryables explode into multiple variations, each needed to be executed at some point). If you break the delayed execution at some point your queries from there will be simplified and faster - then calling .AsQueryable() later would only serve the purpose of fitting the result to a specific (perhaps needed for some api) type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜