[英]Convert IEnumerable<int> to int[]
How do I convert from a IEnumerable variable to an int[] in variable in c#?如何在 c# 中将 IEnumerable 变量转换为 int[] 变量?
Use the .ToArray()
extension method if you're able to use System.Linq如果您能够使用 System.Linq,请使用.ToArray()
扩展方法
If you're in.Net 2 then you could just rip off how System.Linq.Enumerable implements the.如果您在.Net 2 中,那么您可以扯掉 System.Linq.Enumerable 的实现方式。 ToArray
extension method (I've lifted the code here almost verbatim - does it need a Microsoft®?): ToArray
扩展方法(我已经几乎逐字逐句地解除了这里的代码 - 它需要 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;
}
}
With this you simply can do this:有了这个,你可以这样做:
public int[] ToArray(IEnumerable<int> myEnumerable)
{
return new Buffer<int>(myEnumerable).ToArray();
}
IEnumerable<int> i = new List<int>{1,2,3};
var arr = i.ToArray();
IEnumerable to int[] - enumerable.Cast<int>().ToArray();
IEnumerable<int> to int[] - enumerable.ToArray();
IEnumerable<int> ints = new List<int>();
int[] arrayInts = ints.ToArray();
Provided you are using Linq:)如果您使用的是 Linq :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.