Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda