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>();
You can convert ArrayList elements to object[] array using ArrayList. ToArray() method.
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#.
ArrayList is a powerful feature of C# language. It is the non-generic type of collection which is defined in System. Collections namespace.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With