How to easily convert from IEnumerable <T> to list <T>?

I have IEnumerable<Int32>, and I want to convert it to List<Int32>. What is the best way to do this? (no repetition through IEnumerable)

+3
source share
4 answers

You can use ToListthe extension method on IEnumerable<T>or , which accepts . List<T>IEnumerable<T>

IEnumerable<int> numbers = ...;
List<int> numberList = numbers.ToList();
List<int> numberList2 = new List<int>(numbers);

Regardless of what others have said, you will have to list the original Enumerable<int>(whether you do it manually or not), although it is possible that one or both of these methods can work more efficiently than a naive enumeration if the original IEnumerableis equal to List<T>or ICollection<T>.

, IEnumerable, IEnumerable<T>, , Cast<T> IEnumerable

+3

, ToList()

+12

IEnumerable . , IEnumerable < > . ToList(). O (n).

+8
new List(enumerable);

.

, , :

  • List<T> , .
  • List<T>provides methods and properties that it IEnumerable<T>does not have (for example, Count) and which cannot be defined without iterating through all elements.
+2
source

Source: https://habr.com/ru/post/1778346/


All Articles