18

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)));
3
  • yep, i am building a list of Plus5 from a initial list of int Commented Jun 5, 2013 at 22:15
  • Is there a reason you want to have a Plus5 type? It sounds like you may just want to build a new list of int where the ints happen to be incremented by 5 Commented Jun 5, 2013 at 22:16
  • its just for the example Commented Jun 5, 2013 at 22:26

4 Answers 4

24

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)));
Sign up to request clarification or add additional context in comments.

3 Comments

This is a correct answer. However, you may want to suggest an alternative solution where he can create a List<int> such that the ints happen to be incremented by 5 :)
@steaks: It seems as if roughnex has already posted that approach(at least IEnumerable<int>). However, it is not what OP has asked for.
Yeah, thats the correct answer. Thanks you, the +5 were just for the example :D
17

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

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

2 Comments

Great, i didnt realized that Select got that power.
Have a look at this link code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b. Its a great starting place for learning LINQ.
1

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

Comments

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

1 Comment

This won't even compile. You are trying to construct a List<int> by passing in List<Plus5> as a constructor parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.