Convert 'ArrayList' to 'List<string>' (or 'List<T>') using LINQ

66,355

Solution 1

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.

Solution 2

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

Solution 3

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
Share:
66,355
Elvin
Author by

Elvin

Updated on July 09, 2022

Comments

  • Elvin
    Elvin almost 2 years

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