Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda