336

Last night I had dream that the following was impossible. But in the same dream, someone from SO told me otherwise. Hence I would like to know if it it possible to convert System.Array to List

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

to

List<int> lst = ints.OfType<int>(); // not working
Himanshu
  • 31,810
  • 31
  • 111
  • 133
user193276
  • 3,931
  • 3
  • 19
  • 14
  • 2
    Below link show how it does in c# http://www.codegateway.com/2011/12/c-convert-array-to-list-and-list-to.html –  Feb 29 '12 at 17:00
  • 12
    You have to cast the `Array` to what it actually is, an `int[]`, then you can use `ToList`: `((int[])ints).ToList();` – Tim Schmelter Dec 04 '15 at 16:39
  • @naserasadi please consider accepting the answer by Tim Schmelter as this is appears to be the correct answer to your question and even 12 years later this question is showing at the top of search results. Thanks! – David Feb 26 '22 at 18:30
  • Why to use System.Array at the first place? I think that need for using System.Array has died out long time ago. Just use typed arrays like int[] or IMyType[], or Lists... You will never have these type of problems. – A. Dzebo Mar 25 '22 at 09:43
  • 1
    @A.Dzebo Enum.GetValues() returns System.Array. – puzzl Jan 06 '23 at 18:11
  • @puzzl that's fine. Just convert it to a list using i.e. LINQ like this: List data = Enum.GetValues(typeof(Days)).OfType().Select(o => o).ToList(); and work with the list. – A. Dzebo Jan 09 '23 at 14:57

11 Answers11

509

Save yourself some pain...

using System.Linq;

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.

Can also just...

List<int> lst = new List<int> { 10, 20, 10, 34, 113 };

or...

List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);

or...

List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });

or...

var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
Ivan Castellanos
  • 8,041
  • 1
  • 47
  • 42
David
  • 19,389
  • 12
  • 63
  • 87
106

There is also a constructor overload for List that will work... But I guess this would required a strong typed array.

//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);

... for Array class

var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
    intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
  • Between this approach and the one using `ToList()`, which is more efficient? Or is there a difference? – Ben Sutton Jul 04 '12 at 04:27
  • 1
    Hard to say without knowing the real dataset size (List internally uses arrays that must be able to expand. Arrays are immutable.) If you know the List size upfront this way could improve performance slightly… but the gain is going to be so small you may as well use the version you prefer to maintain. – Matthew Whited Jul 05 '12 at 12:32
  • 3
    Have you noticed this thread is 6 years old? (And my second answer directly handles his example of using `Array` instead of `int[]`.) – Matthew Whited Dec 04 '15 at 16:40
102

Interestingly no one answers the question, OP isn't using a strongly typed int[] but an Array.

You have to cast the Array to what it actually is, an int[], then you can use ToList:

List<int> intList = ((int[])ints).ToList();

Note that Enumerable.ToList calls the list constructor that first checks if the argument can be casted to ICollection<T>(which an array implements), then it will use the more efficient ICollection<T>.CopyTo method instead of enumerating the sequence.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 21
    Thank you, `Enum.GetValues` returns an Array and this helped me out making a list out of it. – Martin Braun Aug 28 '16 at 20:57
  • 4
    I know this is old but you are right, the question is answer by this. In my situation a dynamic deserializer returns a system array because it has to be prepared to accept any kind of data type so you can't preload the list until runtime. Thank you – Frank Cedeno May 02 '17 at 14:21
27

The simplest method is:

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.ToList();

or

List<int> lst = new List<int>();
lst.AddRange(ints);
Adam Parkin
  • 17,891
  • 17
  • 66
  • 87
Danny
  • 271
  • 3
  • 2
15

In the case you want to return an array of enums as a list you can do the following.

using System.Linq;

public List<DayOfWeek> DaysOfWeek
{
  get
  {
    return Enum.GetValues(typeof(DayOfWeek))
               .OfType<DayOfWeek>()
               .ToList();
  }
}
Rahbek
  • 1,331
  • 14
  • 9
6

You can do like this basically:

int[] ints = new[] { 10, 20, 10, 34, 113 };

this is your array, and than you can call your new list like this:

 var newList = new List<int>(ints);

You can do this for complex object too.

nzrytmn
  • 6,193
  • 1
  • 41
  • 38
5

in vb.net just do this

mylist.addrange(intsArray)

or

Dim mylist As New List(Of Integer)(intsArray)
Smith
  • 5,765
  • 17
  • 102
  • 161
3

You can just give it try to your code:

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);

ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

int[] anyVariable=(int[])ints;

Then you can just use the anyVariable as your code.

13kudo
  • 41
  • 2
3

I know two methods:

List<int> myList1 = new List<int>(myArray);

Or,

List<int> myList2 = myArray.ToList();

I'm assuming you know about data types and will change the types as you please.

Ashish Neupane
  • 193
  • 2
  • 17
2

Just use the existing method.. .ToList();

   List<int> listArray = array.ToList();

KISS(KEEP IT SIMPLE SIR)

Drew Aguirre
  • 375
  • 2
  • 15
0

I hope this is helpful.

enum TESTENUM
    {
        T1 = 0,
        T2 = 1,
        T3 = 2,
        T4 = 3
    }

get string value

string enumValueString = "T1";

        List<string> stringValueList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m => 
            Convert.ToString(m)
            ).ToList();

        if(!stringValueList.Exists(m => m == enumValueString))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertString;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);

get integer value

        int enumValueInt = 1;

        List<int> enumValueIntList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
            Convert.ToInt32(m)
            ).ToList();

        if(!enumValueIntList.Exists(m => m == enumValueInt))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertInt;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);