开发者

Return Type for Collection from LINQ Query

I have a meth开发者_开发技巧od, that returns a group of accounts

Public Shared Function GetAllNotesByUser(ByVal UserID As Guid) As Account (??)
    Using db As New MyEntity
        Dim query= (From A In db.Account _
                    Where A.aspnet_Users.UserId = UserID _
                    Select A)
        Return query
    End Using
End Function

I would then like to pass this to another function to calculate the totals for all the accounts in the collection. Is it best practice to return an Ienumerable, a generic list, I'm just not sure what works best with LINQ and the entity framework.


When propagating LINQ query results from methods in this manner, the best choice for the return type is IEnumerable(Of T) for LINQ to objects or IQueryable(Of T) for other LINQ providers. In this case it looks like Account is the type so IEnumerable(Of Account) or IQueryable(Of T) depending on the query type in question.


The best type would be

IEnumerable<Account>

or the correspounding syntax in VB :P

Actually, all the LINQ functions (.Where() , .Distinct() etc) are extension methods to IEnumerable<T>, to I think it is good practice to continue the chain in the same way.


There's a good answer here on IEnumerable<T> vs IQueryable<T>.

I would use IQueryable(Of T) if you would like to further limit the set in the caller of the method, for example with a WHERE clause. Otherwise I would use IEnumerable(Of T) if all callers are aware that they need to perform a ToList() on the result if they plan to iterate it more than once (otherwise you would make multiple calls to the database). If callers are not aware, I would probably use ICollection(Of T) and perform the ToList() in the method itself.


The question you need to ask is: "When do I need the SQL to actually be executed?" In LINQ, it's the difference between deferred and immediate execution. Any method that returns an IEnumerable<> has to execute the query in order to get the results. IQueryable<>, on the other hand, delays execution of the query until a method that returns an IEnumerable<> is called against it. In the example you provided, it may be faster to pass the result of the GetAllNotesByUser function as an IQueryable<>, so that you run a single query instead of two:

public static IQueryable<Account> GetAllNotesByUser(Guid UserId)
{
    ...
}

There may be situations where you need to enumerate the result of GetAllNotesByUser without performing any additional manipulation. In those cases, remember you can call 'ToList()` to force execution of the query.

var result = GetAllNotesByUser(<guid>).ToList();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜