El pocho la pantera
El pocho la pantera

Reputation: 505

Create a list from another list

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)));

Upvotes: 18

Views: 50218

Answers (4)

Nick
Nick

Reputation: 4212

List<Plus5> result = new List<Plus5>(InitialList.Select(x=>new Plus5(x)).ToList()));

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

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)));

Upvotes: 24

Shlomo
Shlomo

Reputation: 14370

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();

Upvotes: 1

arunlalam
arunlalam

Reputation: 1848

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

var result = initialList.Select(x => x + 5);

Upvotes: 17

Related Questions