Conversione di System.Array in elenco


279

Ieri sera ho sognato che era impossibile seguire le seguenti affermazioni. Ma nello stesso sogno, qualcuno della SO mi ha detto diversamente. Quindi vorrei sapere se è possibile convertire System.ArrayinList

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);

per

List<int> lst = ints.OfType<int>(); // not working

2
Il link seguente mostra come funziona in c # codegateway.com/2011/12/…

6
Devi lanciare Arrayquello che è in realtà, an int[], quindi puoi usare ToList:((int[])ints).ToList();
Tim Schmelter il

Risposte:


428

Risparmiati un po 'di dolore ...

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.

Può anche solo ...

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 });

15
Nota per completezza: il secondo metodo è disponibile solo in C # 3.0+.
Jon Seigel,

21
Poiché la matrice int implementa già IEnumerable<int>, OfType<int>()non è necessario. ints.ToList();basta.
Heinzi,

16
Per OfType, hai bisogno di System.Linq
JasonPlutext il

11
Nessuno di questi esempi in realtà risponde alla domanda reale. Ma credo che abbia accettato la risposta, quindi era felice. Tuttavia, nessuno di questi in realtà converte un array in un elenco. "Conversione di System.Array in elenco". Dovrebbe aggiungere quell'esempio per completezza IMO. (Essere la risposta migliore e tutto il resto)
Søren Ullidtz il

4
Enum.GetValues ​​(typeof (Enumtype)). Cast <itemtype> (). ToList ()
Phan Đức Bình

84

C'è anche un sovraccarico del costruttore per List che funzionerà ... Ma suppongo che questo richiederebbe un array tipizzato forte.

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

... per la classe 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);

Tra questo approccio e quello che utilizza ToList(), quale è più efficiente? O c'è una differenza?
Ben Sutton,

1
Difficile dirlo senza conoscere le dimensioni reali del set di dati (l'elenco utilizza internamente array che devono essere in grado di espandersi. Gli array sono immutabili). Se si conosce anticipatamente la dimensione dell'elenco in questo modo si potrebbero migliorare leggermente le prestazioni ... ma il guadagno sarà così piccolo che può anche utilizzare la versione che preferisci mantenere.
Matthew Whited,

3
Hai notato che questa discussione ha 6 anni? (E la mia seconda risposta gestisce direttamente il suo esempio di utilizzo Arrayinvece di int[].)
Matthew Whited il

66

È interessante notare che nessuno risponde alla domanda, OP non utilizza un fortemente tipizzato int[]ma un Array.

Devi lanciare Arrayquello che è in realtà, an int[], quindi puoi usare ToList:

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

Si noti che Enumerable.ToListchiama il costruttore dell'elenco che controlla innanzitutto se è possibile eseguire il cast dell'argomento ICollection<T>(che implementa un array), quindi utilizzerà il ICollection<T>.CopyTometodo più efficiente invece di enumerare la sequenza.


11
Grazie, Enum.GetValuesrestituisce un array e questo mi ha aiutato a fare un elenco.
Martin Braun,

3
So che questo è vecchio ma hai ragione, la domanda è la risposta da questo. Nella mia situazione un deserializzatore dinamico restituisce un array di sistema perché deve essere preparato per accettare qualsiasi tipo di tipo di dati in modo da non poter precaricare l'elenco fino al runtime. Grazie
Frank Cedeno,

27

Il metodo più semplice è:

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

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

o

List<int> lst = new List<int>();
lst.AddRange(ints);

7
Uno ha bisogno using System.Linq;per ToList()il lavoro.
Jarekczek,

Questo non funziona per Array. Devi lanciarlo o chiamare .Cast<>prima.
BlueRaja - Danny Pflughoeft il

11

Nel caso in cui si desideri restituire una matrice di enumerazioni come elenco, è possibile effettuare le seguenti operazioni.

using System.Linq;

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

5

In pratica puoi fare così:

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

questo è il tuo array e puoi chiamare il tuo nuovo elenco in questo modo:

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

Puoi farlo anche per oggetti complessi.


4

in vb.net basta farlo

mylist.addrange(intsArray)

o

Dim mylist As New List(Of Integer)(intsArray)

2
molto meglio dell'uso di OfType <> (il mio VS2010 non accetterebbe nulla di OfType ...)
woohoo,

3

Puoi semplicemente provarlo con il tuo codice:

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;

Quindi puoi semplicemente usare anyVariable come codice.


2

Basta usare il metodo esistente .. .ToList ();

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

BACIO (TIENI SEMPLICE SIR)


0

Spero che questo sia utile.

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

ottenere il valore di stringa

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);

ottenere il valore intero

        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);
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.