将IEnumerable<int>转换为int[]

14

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


5
请使用.ToArray()扩展方法。 - Johannes Rudolph
1
给那些给我点“踩”的人:对你来说可能很显而易见,但这值得一个“踩”吗?大多数问题的答案对某些人来说都是显而易见的。 - spender
1
@spender - 就像英国电视节目《谁想成为百万富翁》一样,只有你知道答案,它才显得容易!这不是一个坏问题 - 它完全合理,而且有5个答案表明它是可以回答的。可能会被认为是重复问题。 - Andras Zoltan
是的,似乎有点严厉,因为我在Stackoverflow上至少花了30分钟寻找答案。也许他们今天心情不好。 - Positonic
2
@iKode - 你必须学会忽略那些随意贬低的人。他们是这个网站上不幸的一部分。 - Ritch Melton
@Rich Melton - 谢谢Ritch,这是我第一次遇到这种情况。从现在开始我会注意的 :) - Positonic
5个回答

20

如果可以使用System.Linq,使用.ToArray()扩展方法。

如果您正在使用.NET 2,则可以直接把System.Linq.Enumerable实现的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;
    }
}

通过这个,你可以简单地做到这一点:

public int[] ToArray(IEnumerable<int> myEnumerable)
{
  return new Buffer<int>(myEnumerable).ToArray();
}

16

在使用 LINQ 的 using 指令后,调用 ToArray

using System.Linq;

...

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

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


3
IEnumerable<int> i = new List<int>{1,2,3};
var arr = i.ToArray();

2
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 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接