Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IEnumerable<int> to int[]

How do I convert from a IEnumerable variable to an int[] in variable in c#?

like image 341
iKode Avatar asked Jul 04 '11 10:07

iKode


2 Answers

Use the .ToArray() extension method if you're able to use System.Linq

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();
}
like image 195
Andras Zoltan Avatar answered Sep 19 '22 13:09

Andras Zoltan


Call ToArray after a using directive for LINQ:

using System.Linq;

...

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

This requires .NET 3.5 or higher. Let us know if you're on .NET 2.0.

like image 21
Jon Skeet Avatar answered Sep 16 '22 13:09

Jon Skeet