La conversión de IEnumerable a la Lista [duplicate]


Esta pregunta ya tiene una respuesta aquí:

Quiero convertir de IEnumerable<Contact> a List<Contact>. ¿Cómo puedo hacer esto?

Author: Koterpillar, 2011-10-01

5 answers

Puede hacer esto muy simplemente usando LINQ.

Asegúrese de que este uso esté en la parte superior de su archivo C#:

using System.Linq;

A continuación, utilice el ToList método de extensión.

Ejemplo:

IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();
 336
Author: vcsjones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-07 20:14:50

En caso de que esté trabajando con un viejo System.Collections.IEnumerable normal en lugar de IEnumerable<T> puede usar enumerable.Cast<object>().ToList()

 139
Author: cordialgerm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-01 02:30:11

Si está utilizando una implementación de System.Collections.IEnumerable puede hacer lo siguiente para convertirlo en un List. Los siguientes usos Enumerable.Cast método para convertir IEnumberable a un List Genérico.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

Si está utilizando la versión Genérica IEnumerable<T>, La conversión es sencilla. Dado que ambos son genéricos, puede hacer lo siguiente,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

Pero si el IEnumerable es nulo, cuando intente convertirlo a un List, obtendrá ArgumentNullException decir Valor no puede ser nulo.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

introduzca la descripción de la imagen aquí

Por lo tanto, como se menciona en la otra respuesta , recuerde hacer una verificación null antes de convertirlo a List.

 16
Author: Nipuna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:03:02

Uso un método de extensión para esto. Mi método de extensión primero comprueba si la enumeración es nula y si es así crea una lista vacía. Esto le permite hacer un foreach en él sin tener que verificar explícitamente null.

Aquí hay un ejemplo muy artificial:

IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));

Aquí está el método de extensión:

public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
    return obj == null ? new List<T>() : obj.ToList();
}
 5
Author: Craig B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-04 05:33:24

Otra manera

List<int> list=new List<int>();

IEnumerable<int> enumerable =Enumerable.Range(1, 300);  

foreach (var item in enumerable )  
{     
  list.add(item);  
}
 4
Author: NourAldienArabian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-26 17:45:38