How do I convert an Array to a List<object> in C#?
-
15I don't see what's wrong with this question.. -5? Really?Filip Ekberg– Filip Ekberg2011-02-07 14:47:15 +00:00Commented Feb 7, 2011 at 14:47
-
6+1 because it is a simple, effective question for which I did not find a duplicate on SO. (Downvoters should comment or reconsider.) stackoverflow.com/questions/1003841/… blog.stackoverflow.com/2009/06/podcast-58JYelton– JYelton2011-02-07 16:08:37 +00:00Commented Feb 7, 2011 at 16:08
-
Possible duplicate of Conversion of System.Array to ListJim Fell– Jim Fell2016-06-01 20:27:12 +00:00Commented Jun 1, 2016 at 20:27
13 Answers
List<object> list = myArray.Cast<Object>().ToList();
If the type of the array elements is a reference type, you can leave out the .Cast<object>() since C#4 added interface co-variance i.e. an IEnumerable<SomeClass> can be treated as an IEnumerable<object>.
List<object> list = myArray.ToList<object>();
3 Comments
List<object> list = myArray.ToList<object>();Use the constructor: new List<object>(myArray)
1 Comment
.Contains(userName)). Useful for cramming a bunch of logic into a one-line if statement :) .List<object>.AddRange(object[]) should do the trick. It will avoid all sorts of useless memory allocation.
You could also use Linq, somewhat like this: object[].Cast<object>().ToList()
1 Comment
List<T> - you can Clear() and reuse an existing list.If array item and list item are same
List<object> list=myArray.ToList();
1 Comment
Everything everyone is saying is correct so,
int[] aArray = {1,2,3};
List<int> list = aArray.OfType<int> ().ToList();
would turn aArray into a list, list. However the biggest thing that is missing from a lot of comments is that you need to have these 2 using statements at the top of your class
using System.Collections.Generic;
using System.Linq;
I hope this helps!
Comments
Depending of the Array type.
If you have a function that returns the Array type then:
List<string> x = new List<string>{"a","b","c"};
//this is a none predefined array object.
Array _test = x.ToArray();
If you want to convert the _test back to a List<string>
you can easily do it like this:
List abx = x.getValue(0) as List<string>;
If you a have predefined array object:
string[] arrString = { "A", "B", "C"};
//or
string[] arrstring = string[6];
Then you can cast the arrstring.toList();