How to convert an ArrayList to a strongly typed generic list without using a foreach?

C#.NetListArraylistGeneric List

C# Problem Overview


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;    

      

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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;
    }
}

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames LawrukView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#mqpView Answer on Stackoverflow
Solution 3 - C#Will WMView Answer on Stackoverflow
Solution 4 - C#Sina LotfiView Answer on Stackoverflow