Let\'s say I have:
class Plus5 {
Plus5(int i) {
i+5;
}
}
List initialList = [0,1,2,3]
How I can create, from <
Use LINQ to add 5 to each number in your list.
var result = initialList.Select(x => x + 5);
List<Plus5> result = new List<Plus5>(InitialList.Select(x=>new Plus5(x)).ToList()));
How i can create, from initialList, another list calling Plus5() constructor for each element of initialList?
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)));
You can use LINQ as roughnex mentioned.
var result = initialList.Select(x => x + 5).ToList();
If you had a method (like Plus5), it would look like so
int Plus5(int i)
{
return I + 5;
}
var result = initialList.Select(Plus5).ToList();