Подтвердить что ты не робот

Преобразование IEnumerable <int> в int []

Как преобразовать из переменной IEnumerable в int [] в переменной в С#?

4b9b3361

Ответ 1

Используйте метод расширения .ToArray(), если вы можете использовать System.Linq

Если вы находитесь в .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();
}

Ответ 2

Вызовите ToArray после использования директивы для LINQ:

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();

Ответ 4

IEnumerable to int[] - enumerable.Cast<int>().ToArray();
IEnumerable<int> to int[] - enumerable.ToArray();

Ответ 5

IEnumerable<int> ints = new List<int>();
int[] arrayInts = ints.ToArray();

Если вы используете Linq:)