从另一个列表创建一个列表 [英] Create a list from another list

查看:74
本文介绍了从另一个列表创建一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

class Plus5 {
    Plus5(int i) {
         i+5;
     }
}
List<int> initialList = [0,1,2,3]

如何从initialList创建另一个为initialList的每个元素调用Plus5()构造函数的列表.

How I can create, from initialList, another list calling Plus5() constructor for each element of initialList.

这里有比以下更好的东西吗?

Is here something better than the following?

List<Plus5> newList = new List<Plus5>();
initialList.ForEach( i => newList.Add(Plus5(int)));

推荐答案

我如何从initialList创建另一个调用Plus5()的列表 是否为initialList的每个元素构造函数?

How i can create, from initialList, another list calling Plus5() constructor for each element of initialList?

因此结果为List<Plus5> newList,并且您要为initialList中的每个int创建一个新的Plus5:

So the result is List<Plus5> newList and you want to create a new Plus5 for every int in 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)));

这篇关于从另一个列表创建一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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