Shawn Mclean
Shawn Mclean

Reputation: 57469

Lambda add incremented elements to list

If I have a number and I need to increment it n times and add them to a list, is there a way to do this in 1 line in lambda?

For eg.

int n = 5; //5 elements.
int x = 10; // starts at 10
//do stuff
List<int> list;
//list now contains: 10, 11, 12, 13, 14

Upvotes: 7

Views: 1980

Answers (3)

sll
sll

Reputation: 62544

Just for fun using lambda expression and closure: (I like Enumerable.Range() but also I like a fun whilst approaching different solutions)

var list = new List<int>();            
Action<int, int> generator = (x, n) => { while ( n-- > 0) list.Add(x++); };
generator(10, 5);

Upvotes: 1

asawyer
asawyer

Reputation: 17808

var list = Enumerable.Range(x,n).ToList();

Upvotes: 4

Anthony Pegram
Anthony Pegram

Reputation: 126932

If you want to construct a list with 5 elements from a given starting point, incrementing by one, you can use Enumerable.Range.

var list = Enumerable.Range(10, 5).ToList();

To add those to a pre-existing list, combine it with AddRange

list.AddRange(Enumerable.Range(10, 5));

Upvotes: 16

Related Questions