2011-07-04 31 views
12

Come si converte da una variabile IEnumerable in una [[] in variabile in C#?Converti IEnumerable <int> in int []

+5

utilizzare il .ToArray() metodo di estensione. –

+1

Per i downvoter: per te potrebbe essere ovvio, ma merita un DV? Le risposte alla maggior parte delle domande sono ovvie per qualcuno. – spender

+1

@spender - Come nel gameshow del Regno Unito Chi vuol essere milionario? È semplice se conosci la risposta! Non è una cattiva domanda - è perfettamente ragionevole e 5 risposte dicono che è responsabile. Potrebbe però qualificarsi per un dupe. –

risposta

18

utilizzare il metodo .ToArray() estensione se siete in grado di utilizzare System.Linq

Se siete in Net 2 allora si potrebbe appena strappare quanto System.Linq.Enumerable implementa il. ToArray metodo di estensione (ho sollevato il codice qui quasi parola per parola - ne ha bisogno un Microsoft®?):

struct Buffer<TElement> 
{ 
    internal TElement[] items; 
    internal int count; 
    internal Buffer(IEnumerable<TElement> source) 
    { 
     TElement[] array = null; 
     int num = 0; 
     ICollection<TElement> collection = source as ICollection<TElement>; 
     if (collection != null) 
     { 
      num = collection.Count; 
      if (num > 0) 
      { 
       array = new TElement[num]; 
       collection.CopyTo(array, 0); 
      } 
     } 
     else 
     { 
      foreach (TElement current in source) 
      { 
       if (array == null) 
       { 
        array = new TElement[4]; 
       } 
       else 
       { 
        if (array.Length == num) 
        { 
         TElement[] array2 = new TElement[checked(num * 2)]; 
         Array.Copy(array, 0, array2, 0, num); 
         array = array2; 
        } 
       } 
       array[num] = current; 
       num++; 
      } 
     } 
     this.items = array; 
     this.count = num; 
    } 
    public TElement[] ToArray() 
    { 
     if (this.count == 0) 
     { 
      return new TElement[0]; 
     } 
     if (this.items.Length == this.count) 
     { 
      return this.items; 
     } 
     TElement[] array = new TElement[this.count]; 
     Array.Copy(this.items, 0, array, 0, this.count); 
     return array; 
    } 
} 

Con questo si può semplicemente fare questo:

public int[] ToArray(IEnumerable<int> myEnumerable) 
{ 
    return new Buffer<int>(myEnumerable).ToArray(); 
} 
3
IEnumerable<int> i = new List<int>{1,2,3}; 
var arr = i.ToArray(); 
14

chiamata ToArray dopo una direttiva using per LINQ:

using System.Linq; 

... 

IEnumerable<int> enumerable = ...; 
int[] array = enumerable.ToArray(); 

Richiede .NET 3.5 o versione successiva. Fateci sapere se siete su .NET 2.0.

1
IEnumerable to int[] - enumerable.Cast<int>().ToArray(); 
IEnumerable<int> to int[] - enumerable.ToArray(); 
1
IEnumerable<int> ints = new List<int>(); 
int[] arrayInts = ints.ToArray(); 

A condizione che si sta utilizzando LINQ :)