Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>();
like image 553
Elvin Avatar asked Aug 15 '12 06:08

Elvin


People also ask

Can we convert ArrayList to list?

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

Can we use Linq on ArrayList?

LINQ with ArrayListYou don't need to specify array size unlike traditional array and the size grows as you will add more element into it. However, it is slower than Array but it is more useful when you work with collection. Here, in this example, we will learn how to process data in ArrayList using LINQ C#.

Is ArrayList generic in C#?

ArrayList is a powerful feature of C# language. It is the non-generic type of collection which is defined in System. Collections namespace.


1 Answers

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.

like image 68
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet