转换IEnumerable< int>诠释[] [英] Convert IEnumerable<int> to int[]
本文介绍了转换IEnumerable< int>诠释[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从IEnumerable变量转换为c#中的int []?
How do I convert from a IEnumerable variable to an int[] in variable in c#?
推荐答案
使用 .ToArray()
扩展方法,如果您能够使用System.Linq
Use the .ToArray()
extension method if you're able to use System.Linq
如果您使用的是.Net 2那么您可以只是窃听System.Linq.Enumerable如何实现。 ToArray
扩展方法(我在这里逐字逐句地删除了代码-确实它需要Microsoft®吗?):
If you're in .Net 2 then you could just rip off how System.Linq.Enumerable implements the .ToArray
extension method (I've lifted the code here almost verbatim - does it need a 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>诠释[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文