2011-07-04 114 views
12

如何從一個IEnumerable變量轉換爲int []在c#中的變量?將IEnumerable <int>轉換爲int []

+5

使用.ToArray()擴展方法。 –

+1

對於downvoter(s):對你來說它可能是顯而易見的,但這是否值得DV?大多數問題的答案對某人來說是顯而易見的。 – spender

+1

@spender - 就像在英國的比賽中誰想成爲百萬富翁?如果你知道答案,這很容易! 這不是一個壞問題 - 這是完全合理的,5個答案表示它的答覆。雖然可能有資格獲得複製。 –

回答

18

如果你能如果您在使用.NET 2是,那麼你可以只是撕掉System.Linq.Enumerable如何實現使用System.Linq的

使用.ToArray()擴展方法。 ToArray擴展方法(我幾乎是逐字這裏舉的代碼 - 它需要一個微軟?):

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

有了這個,你簡直可以這樣做:

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

呼叫ToArray在使用LINQ指令後:

using System.Linq; 

... 

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

這需要.NET 3.5或更高版本。讓我們知道您是否使用.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(); 

只要你正在使用LINQ :)

相關問題