C# 如何在不使用 foreach 的情况下将 ArrayList 转换为强类型泛型列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/786268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an ArrayList to a strongly typed generic list without using a foreach?
提问by James Lawruk
See the code sample below. I need the ArrayList
to be a generic List. I don't want to use foreach
.
请参阅下面的代码示例。我需要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;
采纳答案by JaredPar
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 框架中定义的某些扩展方。
回答by mqp
This is inefficient (it makes an intermediate array unnecessarily) but is concise and will work on .NET 2.0:
这是低效的(它不必要地制作了一个中间数组)但简洁并且适用于 .NET 2.0:
List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));
回答by Will WM
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;
}
}
回答by Sina Lotfi
In .Net standard 2 using Cast<T>
is better way:
在 .Net 标准 2 中使用Cast<T>
更好的方:
ArrayList al = new ArrayList();
al.AddRange(new[]{"Micheal", "Hyman", "Sarah"});
List<int> list = al.Cast<int>().ToList();
Cast
andToList
are extension methods in theSystem.Linq.Enumerable
class.
Cast
并且ToList
是System.Linq.Enumerable
类中的扩展方。