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

291
Vistas
¿Hay alguna forma de LINQ de convertir 2 elementos de línea en N según la cantidad?

Aquí hay un código que funciona, pero ¿hay una forma LINQ de convertir 2 elementos de línea en N según la cantidad?

 var list = new List<LineItem>{ new LineItem { Info = "two of these", Quantity = 2 }, new LineItem { Info = "one of these", Quantity = 1 } }; // prints two lines // 2x - two of these // 1x - one of these foreach( var entry in list) Console.WriteLine(entry); Console.WriteLine("now I want three lines printed as for the shopping bag"); // prints threes lines quantity driving that // 2x - two of these // 2x - two of these // 1x - one of these // this works, but is there a clean LINQy way? var bag = new List<LineItem>(); foreach( var item in list) { if ( item.Quantity == 1 ) bag.Add(item); else for ( var count = 0 ; count < item.Quantity ; ++ count) bag.Add(item); } foreach( var entry in bag) Console.WriteLine(entry);
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Puede usar una combinación de SelectMany() y Enumerable.Repeat() para lograr lo que desea aquí. Por ejemplo:

var list2 = list.SelectMany(x => Enumerable.Repeat(x, x.Quantity));

  • SelectMany() selecciona un elemento de cada elemento x de la entrada. Si alguno de estos elementos son secuencias en sí mismos, todos se aplanan en una sola secuencia (en lugar de terminar con una lista de listas)
  • Enumerable.Repeat() crea un nuevo enumerable basado en cada elemento, que contiene el elemento x repetido x.Quantity veces.

Listado completo probado en .NetFiddle: https://dotnetfiddle.net/wpOafs

 using System; using System.Collections.Generic; using System.Linq; public class Program { public class LineItem { public string Info {get;set;} public int Quantity {get;set;} } public static void Main() { var list = new List<LineItem>{ new LineItem { Info = "two of these", Quantity = 2 }, new LineItem { Info = "one of these", Quantity = 1 } }; var list2 = list.SelectMany(x => Enumerable.Repeat(x, x.Quantity)); foreach(var item in list2) { Console.WriteLine(item.Info + item.Quantity); } Console.WriteLine("Hello World"); } }
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