2011-07-04 140 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 :)

相关问题