Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list from another list

Tags:

c#

linq

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)));
like image 298
El pocho la pantera Avatar asked Jun 05 '13 22:06

El pocho la pantera


People also ask

How do you create a list from a different list in Python?

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.

Can we assign a list to another 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.

Can you duplicate a list in Microsoft lists?

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.


2 Answers

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)));
like image 70
Tim Schmelter Avatar answered Sep 22 '22 10:09

Tim Schmelter


Use LINQ to add 5 to each number in your list.

var result = initialList.Select(x => x + 5);
like image 39
arunlalam Avatar answered Sep 20 '22 10:09

arunlalam