Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda add incremented elements to list

Tags:

c#

lambda

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
like image 208
Shawn Mclean Avatar asked Nov 15 '11 21:11

Shawn Mclean


3 Answers

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));
like image 109
Anthony Pegram Avatar answered Oct 03 '22 09:10

Anthony Pegram


var list = Enumerable.Range(x,n).ToList();
like image 36
asawyer Avatar answered Oct 03 '22 09:10

asawyer


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);
like image 20
sll Avatar answered Oct 03 '22 09:10

sll