简体   繁体   English

如何在不使用foreach的情况下将ArrayList转换为强类型通用列表?

[英]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. 我需要ArrayList作为通用List。 I don't want to use foreach . 我不想使用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;    

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. 这只能使用C#3.5编译器,因为它利用了3.5框架中定义的某些扩展方法。

这是低效的(它不必要地创建一个中间数组)但是简洁并且可以在.NET 2.0上运行:

List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));

How about using an extension method? 使用扩展方法怎么样?

From http://www.dotnetperls.com/convert-arraylist-list : 来自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;
    }
}

In .Net standard 2 using Cast<T> is better way: 在.Net标准2中使用Cast<T>是更好的方法:

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. CastToListSystem.Linq.Enumerable类中的扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM