Is it required or not to use ToList() after Select() in this code:
var names = someStorage.GetItems().Select(x => x.Name).ToList();
The Enumerable.ToList method will cause the population of data, if you do not call data wont be fetched and it will be a query.
The ToList(IEnumerable) method forces immediate query evaluation and returns a List that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results, MSDN.
It completely depends on what your code does subsequently. The ToList()
method causes the query that you defined by using Select()
to run immediately against the datastore. Without it, its execution would be delayed until you access the names
variable for the first time.
The other aspect is that, if you don't use ToList()
, the query will be run against the datastore each time you use the names
variable - not just once as is the case with ToList()
. So it also heavily depends on how often you use the names
variable (If you use it only once (e.g. in a loop), then there is no difference, otherwise ToList()
is much more efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With