Convert IEnumerable To List
Solution 1
They take more or less the same time to execute but new List<T>(myEnumerable)
is a bit faster.
myEnumerable.ToList()
will do a new List<T>(myEnumerable)
under the hood, but it will first check if the collection is null and throw an exception if it is. If you know that myEnumerable is not null then you could use the ToList().
But, in my opinion, write the code that is easiest to read. This is a micro optimization that you should not spend too much time on.
Solution 2
The first calls the second, so they will be to all intents and purposes identical.
The JITter may well inline the ToList()
method which will make them identical modulo a null check. And arguably the null check in Enumerable<T>.ToList()
is redundant, since the List<T>
constructor it calls also performs a null check.
Solution 3
Would be the same. (First is more readable.)
Related videos on Youtube
user436862
Updated on June 04, 2022Comments
-
user436862 almost 2 years
If i want to convert Enumerable (
IEnumerable<T>
) to list.What is more efficient:
myEnumerable.ToList()
or
new List<T>(myEnumerable)
Thanks!
-
Nahum almost 11 yearsI am too lazy to use refletor but probably
myEnumerable.ToList()
callsnew List<T>(myEnumerable)