68

See the code sample below. I need the ArrayList to be a generic List. I don't want to use foreach.

ArrayList arrayList = GetArrayListOfInts();  
List<int> intList = new List<int>();  

//Can this foreach be condensed into one line?  
foreach (int number in arrayList)  
{  
    intList.Add(number);  
}  
return intList;    
1

4 Answers 4

129

Try the following

var list = arrayList.Cast<int>().ToList();

This will only work though using the C# 3.5 compiler because it takes advantage of certain extension methods defined in the 3.5 framework.

4
  • While I've certainly used this before myself, I'm considering boxing/unboxing. Won't that retract from performance? Sometimes I find that pretty code is at the expense of speed and resources...
    – J. Steen
    Apr 24, 2009 at 15:15
  • 7
    That's just a consequence of putting it in an ArrayList in the first place. Just casting every member back to an int is pretty much the best you can do performance-wise.
    – mqp
    Apr 24, 2009 at 15:17
  • @mquander, true, true... I just realized the for-loop in the OP's post does just that as well. =)
    – J. Steen
    Apr 24, 2009 at 15:18
  • Somehow, I missed Cast<> in the System.Linq namespace. I wrote my own extension method that I can remove now. Thanks! Apr 24, 2009 at 15:20
10

This is inefficient (it makes an intermediate array unnecessarily) but is concise and will work on .NET 2.0:

List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));
1
  • 6
    I did arrayList.ToArray(typeof(int)) as int[] and then it worked thanks! +1 Apr 15, 2010 at 7:21
4

How about using an extension method?

From http://www.dotnetperls.com/convert-arraylist-list:

using System;
using System.Collections;
using System.Collections.Generic;

static class Extensions
{
    /// <summary>
    /// Convert ArrayList to List.
    /// </summary>
    public static List<T> ToList<T>(this ArrayList arrayList)
    {
        List<T> list = new List<T>(arrayList.Count);
        foreach (T instance in arrayList)
        {
            list.Add(instance);
        }
        return list;
    }
}
3

In .Net standard 2 using Cast<T> is better way:

ArrayList al = new ArrayList();
al.AddRange(new[]{"Micheal", "Jack", "Sarah"});
List<int> list = al.Cast<int>().ToList();

Cast and ToList are extension methods in the System.Linq.Enumerable class.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.