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

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.