Conversión de System.Array a List

279

Anoche soñé que lo siguiente era imposible. Pero en el mismo sueño, alguien de SO me dijo lo contrario. Por lo tanto, me gustaría saber si es posible convertir System.ArrayaList

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

a

List<int> lst = ints.OfType<int>(); // not working
usuario193276
fuente
2
El siguiente enlace muestra cómo funciona en c # codegateway.com/2011/12/…
66
Tienes que lanzar Arraylo que realmente es, int[]y luego puedes usar ToList:((int[])ints).ToList();
Tim Schmelter

Respuestas:

428

Ahórrate un poco de dolor ...

using System.Linq;

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.

También puede simplemente ...

List<int> lst = new List<int> { 10, 20, 10, 34, 113 };

o...

List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);

o...

List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });

o...

var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
Dave
fuente
15
Nota para completar: el segundo método solo está disponible en C # 3.0+.
Jon Seigel
21
Como la matriz int ya se implementa IEnumerable<int>, OfType<int>()no se requiere. ints.ToList();es suficiente
Heinzi
16
Para OfType, necesita System.Linq
JasonPlutext
11
Ninguno de estos ejemplos responde realmente a la pregunta real. Pero supongo que aceptó la respuesta, así que estaba feliz. Aún así, ninguno de estos convierte realmente una matriz en una lista. "Conversión de System.Array a List". Debería agregar ese ejemplo para completar IMO. (Siendo la primera respuesta y todo)
Søren Ullidtz
44
Enum.GetValues ​​(typeof (Enumtype)). Cast <itemtype> () .ToList ()
Phan Đức Bình
84

También hay una sobrecarga del constructor para List que funcionará ... Pero supongo que esto requeriría una matriz tipada fuerte.

//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);

... para la clase Array

var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
    intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);
Matthew Whited
fuente
Entre este enfoque y el que usa ToList(), ¿cuál es más eficiente? ¿O hay alguna diferencia?
Ben Sutton
1
Es difícil de decir sin conocer el tamaño real del conjunto de datos (List utiliza internamente matrices que deben poder expandirse. Las matrices son inmutables). Si conoce el tamaño de List por adelantado, podría mejorar ligeramente el rendimiento ... pero la ganancia será tan pequeña que también puede usar la versión que prefiera mantener.
Matthew Whited
3
¿Has notado que este hilo tiene 6 años? (Y mi segunda respuesta maneja directamente su ejemplo de uso en Arraylugar de int[])
Matthew Whited
66

Curiosamente nadie responde a la pregunta, OP no está utilizando un inflexible int[], sino una Array.

Tienes que lanzar Arraylo que realmente es, int[]y luego puedes usar ToList:

List<int> intList = ((int[])ints).ToList();

Tenga en cuenta que Enumerable.ToListllama al constructor de la lista que primero verifica si el argumento se puede convertir ICollection<T>(que implementa una matriz), luego usará el ICollection<T>.CopyTométodo más eficiente en lugar de enumerar la secuencia.

Tim Schmelter
fuente
11
Gracias, Enum.GetValuesdevuelve una matriz y esto me ayudó a hacer una lista.
Martin Braun
3
Sé que esto es viejo pero tienes razón, la pregunta es la respuesta con esto. En mi situación, un deserializador dinámico devuelve una matriz del sistema porque tiene que estar preparado para aceptar cualquier tipo de datos para que no pueda precargar la lista hasta el tiempo de ejecución. Gracias
Frank Cedeno
27

El método más simple es:

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.ToList();

o

List<int> lst = new List<int>();
lst.AddRange(ints);
Danny
fuente
77
Uno necesita using System.Linq;para ToList()el trabajo.
Jarekczek
Esto no funciona para Array. Necesitas lanzarlo o llamar .Cast<>primero.
BlueRaja - Danny Pflughoeft
11

En el caso de que desee devolver una matriz de enumeraciones como una lista, puede hacer lo siguiente.

using System.Linq;

public List<DayOfWeek> DaysOfWeek
{
  get
  {
    return Enum.GetValues(typeof(DayOfWeek))
               .OfType<DayOfWeek>()
               .ToList();
  }
}
Rahbek
fuente
5

Puedes hacer esto básicamente:

int[] ints = new[] { 10, 20, 10, 34, 113 };

esta es su matriz, y entonces puede llamar a su nueva lista de esta manera:

 var newList = new List<int>(ints);

También puedes hacer esto para objetos complejos.

nzrytmn
fuente
4

en vb.net solo haz esto

mylist.addrange(intsArray)

o

Dim mylist As New List(Of Integer)(intsArray)
Herrero
fuente
2
mucho mejor que usar OfType <> (mi VS2010 no aceptaría nada de OfType ...)
woohoo
3

Simplemente puede intentarlo con su código:

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);

ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

int[] anyVariable=(int[])ints;

Entonces puede usar anyVariable como su código.

13kudo
fuente
2

Simplemente use el método existente .. .ToList ();

   List<int> listArray = array.ToList();

BESO (MANTÉNGALO SIR SIMPLE)

Drew Aguirre
fuente
0

Espero que esto sea útil.

enum TESTENUM
    {
        T1 = 0,
        T2 = 1,
        T3 = 2,
        T4 = 3
    }

obtener valor de cadena

string enumValueString = "T1";

        List<string> stringValueList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m => 
            Convert.ToString(m)
            ).ToList();

        if(!stringValueList.Exists(m => m == enumValueString))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertString;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);

obtener valor entero

        int enumValueInt = 1;

        List<int> enumValueIntList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
            Convert.ToInt32(m)
            ).ToList();

        if(!enumValueIntList.Exists(m => m == enumValueInt))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertInt;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);
Арсений Савин
fuente