Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToList() after Select() in linq

Tags:

c#

linq

Is it required or not to use ToList() after Select() in this code:

var names = someStorage.GetItems().Select(x => x.Name).ToList();
like image 953
mtkachenko Avatar asked Dec 15 '22 03:12

mtkachenko


2 Answers

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.

like image 198
Adil Avatar answered Jan 01 '23 18:01

Adil


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.

like image 40
Thomas Weller Avatar answered Jan 01 '23 18:01

Thomas Weller