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
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));
var list = Enumerable.Range(x,n).ToList();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With