Elvin
Elvin

Reputation: 2291

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

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

Upvotes: 22

Views: 81804

Answers (4)

Trevor
Trevor

Reputation: 4860

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

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94625

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499760

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.

Upvotes: 37

Related Questions