将IEnumerable 转换为int

如何在c#中将IEnumerable变量转换为变量中的int []?

如果您能够使用System.Linq,请使用.ToArray()扩展方法

如果你在.Net 2中,那么你可以扯掉System.Linq.Enumerable如何实现它。 ToArray扩展方法(我几乎逐字逐句地提取了代码 – 它需要Microsoft®吗?):

 struct Buffer { internal TElement[] items; internal int count; internal Buffer(IEnumerable source) { TElement[] array = null; int num = 0; ICollection collection = source as ICollection; 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 myEnumerable) { return new Buffer(myEnumerable).ToArray(); } 

在LINQ的using指令之后调用ToArray

 using System.Linq; ... IEnumerable enumerable = ...; int[] array = enumerable.ToArray(); 

这需要.NET 3.5或更高版本。 如果您使用的是.NET 2.0,请告诉我们。

 IEnumerable i = new List{1,2,3}; var arr = i.ToArray(); 
 IEnumerable to int[] - enumerable.Cast().ToArray(); IEnumerable to int[] - enumerable.ToArray(); 
 IEnumerable ints = new List(); int[] arrayInts = ints.ToArray(); 

如果你使用Linq 🙂