329

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
6
  • 2
    Below link show how it does in c# codegateway.com/2011/12/…
    – user1240789
    Feb 29, 2012 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(); Dec 4, 2015 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, 2022 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, 2022 at 9:43
  • 1
    @A.Dzebo Enum.GetValues() returns System.Array.
    – puzzl
    Jan 6 at 18:11

11 Answers 11

503

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 });
13
  • 17
    Note for completeness: the 2nd method is only available in C# 3.0+.
    – Jon Seigel
    Oct 21, 2009 at 20:17
  • 25
    Since the int array already implements IEnumerable<int>, the OfType<int>() is not required. ints.ToList(); suffices.
    – Heinzi
    Feb 29, 2012 at 17:06
  • 16
    For OfType, you need System.Linq Jul 27, 2012 at 3:18
  • 17
    None of these examples actually answer the actual question. But I guess he accepted the answer so he was happy. Still, not one of these actually convert an Array to a List. "Conversion of System.Array to List". Should add that example for completeness IMO. (Being top answer and all) Jan 22, 2015 at 8:14
  • 7
    Enum.GetValues(typeof(Enumtype)).Cast<itemtype>().ToList() Jan 5, 2017 at 4:41
104

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);
3
  • Between this approach and the one using ToList(), which is more efficient? Or is there a difference?
    – Ben Sutton
    Jul 4, 2012 at 4: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. Jul 5, 2012 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[].) Dec 4, 2015 at 16:40
95

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.

2
  • 18
    Thank you, Enum.GetValues returns an Array and this helped me out making a list out of it. Aug 28, 2016 at 20:57
  • 3
    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 May 2, 2017 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);
3
  • 7
    One needs using System.Linq; for ToList() to work.
    – Jarekczek
    Jan 7, 2018 at 14:41
  • 2
    This doesn't work for Array. You need to cast it or call .Cast<> first. Jun 21, 2020 at 21:49
  • 1
    have you tested this?
    – David
    Feb 26, 2022 at 18:34
14

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

in vb.net just do this

mylist.addrange(intsArray)

or

Dim mylist As New List(Of Integer)(intsArray)
1
  • 2
    much better than using OfType<> (my VS2010 would not accept anything OfType...) Apr 18, 2012 at 20:55
5

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.

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.

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.

1
  • 1
    This appears to be just a repeat of the existing answers.
    – Pang
    Jan 1, 2021 at 8:04
2

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

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

KISS(KEEP IT SIMPLE SIR)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.