Return type for collection from LINQ query

I have a method 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 like to pass this to another function to calculate totals for all accounts in the collection. It is best to return Ienumerable, a generic list, I'm just not sure what works best with LINQ and entity infrastructure.

+6
linq entity entity-framework
source share
4 answers

When distributing LINQ query results from methods in this way, the best choice for the return type is IEnumerable(Of T) for LINQ for objects or IQueryable(Of T) for other LINQ providers. In this case, it looks like this: Account is the type IEnumerable(Of Account) or IQueryable(Of T) depending on the type of request.

+7
source share

The best type would be

 IEnumerable<Account> 

or the corresponding syntax in VB: P

In fact, all LINQ functions ( .Where() , .Distinct() , etc.) are extension methods to IEnumerable<T> , and I think it's good practice to continue the chains in the same way.

+2
source share

Here is a good answer here on IEnumerable<T> vs IQueryable<T> .

I would use IQueryable(Of T) if you want to further restrict the set in the calling method, for example, with a WHERE clause. Otherwise, I would use IEnumerable(Of T) if all the callers know that they need to execute ToList () for the result if they plan to repeat it several times (otherwise you would make several calls to the database). If callers do not know, I would probably use ICollection(Of T) and execute ToList () in the method itself.

+1
source share

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

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

There may be situations when you need to list the result of GetAllNotesByUser without any additional manipulations. In these cases, remember that you can call 'ToList () `to force the request.

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

All Articles