如何在不使用 foreach 的情况下将 ArrayList 转换为强类型泛型列表? [英] How to convert an ArrayList to a strongly typed generic list without using a foreach?

查看:34
本文介绍了如何在不使用 foreach 的情况下将 ArrayList 转换为强类型泛型列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的代码示例.我需要 ArrayList 成为通用列表.我不想使用 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;    

推荐答案

尝试以下方法

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

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

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.

这篇关于如何在不使用 foreach 的情况下将 ArrayList 转换为强类型泛型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆