2011-07-04 21 views
12

Jak przekonwertować zmienną IEnumerable na int [] w zmiennej w C#?Konwertuj IEnumerable <int> na int []

+5

użyć .ToArray() metodę rozszerzenia. –

+1

Do downvoter (s): dla ciebie może to być oczywiste, ale czy to zasługuje na DV? Odpowiedzi na większość pytań są dla kogoś oczywiste. – spender

+1

@spender - Jak w przypadku gier w Wielkiej Brytanii Kto chce zostać milionerem? To proste, jeśli znasz odpowiedź! To nie jest złe pytanie - jest całkowicie rozsądne, a 5 odpowiedzi mówi, że to jest odpowiedzialne. Może kwalifikować się do dupy. –

Odpowiedz

18

Użyj metody .ToArray() przedłużacza, jeśli jesteś w stanie wykorzystać System.Linq

Jeśli jesteś w .Net 2 wtedy mógłby tylko zdzierać jak System.Linq.Enumerable realizuje. ToArray metodę rozszerzenia (mam podniósł kod tutaj niemal dosłownie - to trzeba 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; 
    } 
} 

Mając to po prostu może to zrobić:

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

połączenia ToArray po zastosowaniu dyrektywy dla LINQ:

using System.Linq; 

... 

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

Wymaga to .NET 3.5 lub nowszej. Daj nam znać, jeśli korzystasz z .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(); 

warunkiem używasz Linq :)