Reputation:
i just don't understand the meaning of writing AsEnumerable() in linq query.
i am having one UserDetail table in which i am fetching all details of user and i want to take name,email in to my model.
var data = context.UserDetails
.Select(temp => new FullName = temp.Fullname, Email = temp.Email })
.ToList()
.AsEnumerable()
.Select(d => new UserDetailsModel { Fullname = d.FullName, Email = d.Email })
.ToList();
What is the meaning of AsEnumerable() as because when i am removing this there is no error but as i have seen some queries where they are using this method.
And does anybody have better approach for taking anonymous object value in to my View Model?
Does it improve performance? What is the significance of this method? Can anybody explain me this method in context to my question and details?
Upvotes: 1
Views: 1845
Reputation:
Your first select
is querying the database and returns IQueryable<T>
. .AsEnumerable()
make it IEnumerable<T>
. IQueryable<T>
extends IEnumerable<T>
so whatever you can do with IEnumerable<T>
, you can also do with IQueryable<T>
.
Another big difference is that IEnumerable<T>
fetches the entire table and applies the query on that afterwards, whereas IQueryable<T>
only fetches the filtered data.
Note that AsEnumerable()
does not materialise the query yet. You often use .ToList()
to materialize your query so other non sql statements can be performed on the result set as per this example
You can simplify your code to
var data = (from temp in context.UserDetails select temp)
.Select(d => new UserDetailsModel
{
Fullname = d.fullName,
Email = d.Email
}).ToList());
Upvotes: 1
Reputation: 14944
ToList()
or AsEnumerable()
work similarly, you don't need both. List
is a IEnumerable
+ some extra features such as Add(), Count, etc., and the idea of using any of these is to materialize the query (IQueryable
).
Also, You don't need the temp query, you could do a direct select:
var data = context.UserDetails
.Select(d => new UserDetailsModel {...})
.ToList()); // or AsEnumerable()
Upvotes: 0