Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
What's the equivalent of JavaScript Array.from in C# (without while/for)?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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().
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!