I'm getting used to JS after a few years of Node.js programming and I'm wondering how we could avoid while loops in C# to add items in an array by using a more "map-like" method (like AddRange in C# enumerables).
For example, if I want an array of 10 elements in JavaScript, each having a property that is incremented each time, I would do:
const cells = Array.from({ length:10 }, (_, i) => { 'number': i });
// gives cells = [{number: 0}, {number: 1}, ... until 9]
How to do that in C# without a while or for loop ?
int itemWantedCount = 10;
int i = 0;
while(cells.Count < itemWantedCount)
{
cells.Add(new MyObject(i++));
}
I'd like to find a method to use cells.AddRange instead, without for/while usage, if that's possible.
You can use LINQ for functional-style list processing in C#. Example:
// We don't need Select in this toy example, but this is where
// you would put your "map" operation.
var cells = Enumerable.Range(0, 10).Select(i => i).ToArray();
// prints 0123456789
foreach (var c in cells)
Console.Write(c);
Explanation:
Enumerable.Range(start, count) enumerates our numbers (lazily - nothing happens until the call to ToArray() later).Select is "map" - you are already familiar with that. In your example, you'd replace i => i with i => new MyObject(i).ToArray(): Materializes the lazily created enumeration. Since arrays are fixed-size in C#, a more idiomatic alternative would be ToList().