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.
Is here something better than the following?
List<Plus5> newList = new List<Plus5>();
initialList.ForEach( i => newList.Add(Plus5(int)));
Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list.
When you copying a list to another list using = sign, both the list refer to the same list object in the memory. So modifying one list, other automatically changes as they both refer to same object. To copy a list use slice operator or copy module.
To duplicate a list, you'll first need to make sure that context menus have been enabled in your app settings. Then just right- or control-click the name of the list you would like to copy in the sidebar to access the context menu. There, you'll have the option to Duplicate list.
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)));
Use LINQ to add 5 to each number in your list.
var result = initialList.Select(x => x + 5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With