Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the number of text strings arrays to 15

Tags:

c#

How to limit the lines pulled from the document to 15 lines at a time. Right now it displays all the lines at once. thanks.

class Program {
  static void Main(string[] args) {
    string[] lines = System.IO.File.ReadAllLines(
        @"C:\Users\chri749y\Documents\Skrive til fil\Testprogram.txt");

    foreach (string line in lines) {
        Console.WriteLine("{0}", line);
    }

    Console.ReadKey();
  }
}
like image 459
Christoffer Larsen Avatar asked Dec 14 '22 16:12

Christoffer Larsen


1 Answers

If you want top 15 lines only, try Take (Linq) which is specially designed for this:

var lines = System.IO.File
  .ReadLines(@"C:\Users\chri749y\Documents\Skrive til fil\Testprogram.txt")
  .Take(15);

In case you want batch processing i.e. get 0 .. 14 lines then 15 .. 29 lines etc.

// Split input into batches with at most "size" items each
private static IEnumerable<T[]> Batch<T>(IEnumerable<T> lines, int size) {
  List<T> batch = new List<T>(size);

  foreach (var item in lines) {
    if (batch.Count >= size) {
      yield return batch.ToArray();

      batch.Clear();
    }

    batch.Add(item);
  }

  if (batch.Count > 0)   // tail, possibly incomplete batch
    yield return batch.ToArray();
}

Then

var batches = Batch(System.IO.File
  .ReadLines(@"C:\Users\chri749y\Documents\Skrive til fil\Testprogram.txt"),
               15);

foreach (var batch in batches) { // Array with at most 15 items
  foreach (var line in batch) {  
    ... 
  }
}
like image 179
Dmitry Bychenko Avatar answered Jan 06 '23 08:01

Dmitry Bychenko