Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;    
like image 789
James Lawruk Avatar asked Apr 24 '09 15:04

James Lawruk


People also ask

How to convert ArrayList into List in c#?

Cast<int>(). ToList();

What is the difference between ArrayList and generics?

Generic List stores all data of the data type it is declared thus to getting the data back is hassle free and no type conversions required. 4. Generic List must be used instead of ArrayList unless specific requirement for projects higher than . Net 2.0 Framework.


3 Answers

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.

like image 113
JaredPar Avatar answered Sep 17 '22 14:09

JaredPar


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)));
like image 45
mqp Avatar answered Sep 21 '22 14:09

mqp


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;
    }
}
like image 26
Will WM Avatar answered Sep 21 '22 14:09

Will WM