C# 从另一个列表创建一个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16950731/
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
Create a list from another list
提问by El pocho la pantera
Let's say I have:
假设我有:
class Plus5 {
Plus5(int i) {
i+5;
}
}
List<int> initialList = [0,1,2,3]
How I can create, from initialList, another list calling Plus5()constructor for each element of initialList.
我如何从为initialList 的每个元素创建initialList另一个调用Plus5()构造函数的列表。
Is here something better than the following?
这里有什么比下面更好的吗?
List<Plus5> newList = new List<Plus5>();
initialList.ForEach( i => newList.Add(Plus5(int)));
回答by arunlalam
Use LINQ to add 5 to each number in your list.
使用 LINQ 将 5 添加到列表中的每个数字。
var result = initialList.Select(x => x + 5);
回答by Tim Schmelter
How i can create, from initialList, another list calling Plus5() constructor for each element of initialList?
我如何从initialList 为initialList 的每个元素创建另一个调用Plus5() 构造函数的列表?
So the result is List<Plus5> newListand you want to create a new Plus5for every intin initialList:
所以结果是List<Plus5> newList你想Plus5为每个intin创建一个新的initialList:
List<Plus5> newList = initialList.Select(i => new Plus5(i)).ToList();
If you want to micro-optimize(save memory):
如果要微优化(节省内存):
List<Plus5> newList = new List<Plus5>(initialList.Count);
newList.AddRange(initialList.Select(i => new Plus5(i)));
回答by Shlomo
You can use LINQ as roughnex mentioned.
您可以使用 LINQ 作为提到的 rawnex。
var result = initialList.Select(x => x + 5).ToList();
If you had a method (like Plus5), it would look like so
如果你有一个方法(比如 Plus5),它看起来像这样
int Plus5(int i)
{
return I + 5;
}
var result = initialList.Select(Plus5).ToList();
回答by Nikola Mitev
List<Plus5> result = new List<Plus5>(InitialList.Select(x=>new Plus5(x)).ToList()));

