【问题标题】:How to convert an ArrayList to a strongly typed generic list without using a foreach?如何在不使用 foreach 的情况下将 ArrayList 转换为强类型泛型列表?
【发布时间】:2010-10-21 15:19:35
【问题描述】:

请参阅下面的代码示例。我需要ArrayList 是一个通用列表。我不想使用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# .net list arraylist generic-list


【解决方案1】:

试试下面的

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

这仅在使用 C# 3.5 编译器时才有效,因为它利用了 3.5 框架中定义的某些扩展方法。

【讨论】:

  • 虽然我自己之前确实使用过这个,但我正在考虑装箱/拆箱。这不会从表演中撤回吗?有时我发现漂亮的代码是以牺牲速度和资源为代价的......
  • 这只是首先将其放入 ArrayList 的结果。仅将每个成员都转换回 int 几乎是您在性能方面可以做到的最好的。
  • @mquander,真的,真的......我刚刚意识到 OP 帖子中的 for 循环也可以做到这一点。 =)
  • 不知何故,我错过了 System.Linq 命名空间中的 Cast。我编写了自己的扩展方法,现在可以删除。谢谢!
【解决方案2】:

这是低效的(它不必要地创建了一个中间数组)但简洁并且适用于 .NET 2.0:

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

【讨论】:

  • 我做了arrayList.ToArray(typeof(int)) as int[] 然后它工作了谢谢! +1
【解决方案3】:

使用扩展方法怎么样?

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

【讨论】:

    【解决方案4】:

    在 .Net 标准 2 中使用 Cast&lt;T&gt; 是更好的方法:

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

    CastToListSystem.Linq.Enumerable 类中的扩展方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2021-01-13
      • 2018-01-01
      相关资源
      最近更新 更多