22

I want to convert an ArrayList to a List<string> using LINQ. I tried ToList() but that approach is not working:

ArrayList resultsObjects = new ArrayList();
List<string> results = resultsObjects.ToList<string>();
DavidRR
  • 18,291
  • 25
  • 109
  • 191
Elvin
  • 2,131
  • 8
  • 23
  • 25
  • 1
    Possible duplicate of [In .Net, how do you convert an ArrayList to a strongly typed generic list without using a foreach?](http://stackoverflow.com/questions/786268/in-net-how-do-you-convert-an-arraylist-to-a-strongly-typed-generic-list-withou) – Michael Freidgeim May 12 '16 at 23:53

4 Answers4

37

Your code actually shows a List<ArrayList> rather than a single ArrayList. If you're really got just one ArrayList, you'd probably want:

ArrayList resultObjects = ...;
List<string> results = resultObjects.Cast<string>()
                                    .ToList();

The Cast call is required because ArrayList is weakly typed - it only implements IEnumerable, not IEnumerable<T>. Almost all the LINQ operators in LINQ to Objects are based on IEnumerable<T>.

That's assuming the values within the ArrayList really are strings. If they're not, you'll need to give us more information about how you want each item to be converted to a string.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

I assume your first line was meant to be ArrayList resultsObjects = new ArrayList();.

If the objects inside the ArrayList are of a specific type, you can use the Cast<Type> extension method:

List<string> results = resultsObjects.Cast<string>().ToList();

If there are arbitrary objects in ArrayList which you want to convert to strings, you can use this:

List<string> results = resultsObjects.Cast<object>().Select(x => x.ToString())
                                                    .ToList();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

You can also use LINQ's OfType<> method, depending on whether you want to raise an exception if one of the items in your arrayList is not castable to the desired type. If your arrayList has objects in it that aren't strings, OfType() will ignore them.

var oldSchoolArrayList = new ArrayList() { "Me", "You", 1.37m };
var strings = oldSchoolArrayList.OfType<string>().ToList();
foreach (var s in strings)
    Console.WriteLine(s);

Output:

Me
You
Trevor
  • 4,620
  • 2
  • 28
  • 37
0

You can convert ArrayList elements to object[] array using ArrayList.ToArray() method.

 List<ArrayList> resultsObjects = new List<ArrayList>();
 resultsObjects.Add(new ArrayList() { 10, "BB", 20 });
 resultsObjects.Add(new ArrayList() { "PP", "QQ" });

 var list = (from arList in resultsObjects
                       from sr in arList.ToArray()
                        where sr is string 
                         select sr.ToString()).ToList();
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186