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

271
Views
Procese una lista con un ciclo, tomando 100 elementos cada vez y automáticamente menos de 100 al final de la lista

¿Hay alguna manera de usar un bucle que tome los primeros 100 elementos en una lista grande, haga algo con ellos, luego los siguientes 100, etc., pero cuando se acerca al final, acorta automáticamente el paso "100" a los elementos restantes?

Actualmente tengo que usar dos bucles if:

 for (int i = 0; i < listLength; i = i + 100) { if (i + 100 < listLength) { //Does its thing with a bigList.GetRange(i, 100) } else { //Does the same thing with bigList.GetRange(i, listLength - i) } }

¿Hay una mejor manera de hacer esto? Si no, al menos haré que la "cosa" sea una función para que el código no tenga que copiarse dos veces.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede utilizar LINQ Skip and Take y su código será más limpio.

 for (int i = 0; i < listLength; i=i+100) { var items = bigList.Skip(i).Take(100); // Do something with 100 or remaining items }

Nota: Si los artículos son menos de 100, Take le daría los restantes.

over 4 years ago · Santiago Trujillo Report

0

No me gustó ninguna de las respuestas enumeradas, así que hice mi propia extensión:

 public static class IEnumerableExtensions { public static IEnumerable<IEnumerable<T>> MakeGroupsOf<T>(this IEnumerable<T> source, int count) { var grouping = new List<T>(); foreach (var item in source) { grouping.Add(item); if(grouping.Count == count) { yield return grouping; grouping = new List<T>(); } } if (grouping.Count != 0) { yield return grouping; } } }

Entonces puedes usarlo:

 foreach(var group in allItems.MakeGroupsOf(100)) { // Do something }
over 4 years ago · Santiago Trujillo Report

0

Puede mantener una variable explícita para el punto final:

 for (int i = 0, j; i < listLength; i = j) { j = Math.min(listLength, i + 100); // do your thing with bigList.GetRange(i, j) }
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!