user3352356
user3352356

Reputation: 27

Split list in foreach loop to add new line each iteration

I want to print all the data line by line where each line contains "n" number of digits, n being user defined. Something like:

void Print(List<int> list, int charactersPerLine)
{
  // TODO: magic here
}

Usage

List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 }
Print(list, 4);

Desired output:

1234
5678

So far I tried:

List.AddRange(array);
List.Add(array2);
List.Add(array3);
foreach (int i in List)
{
     Console.Write("{0}", i);
}

and when the loop writes to the console everything in the List<int> is written in a line, and the output is like:

12345678

Is this possible?

Upvotes: 2

Views: 3242

Answers (3)

Grozz
Grozz

Reputation: 8435

More generic version:

static class LinqExtensions
{
    public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize) 
    {
        int currentBatchSize = 0;
        List<T> batch = new List<T>();

        foreach (var e in source)
        {
            batch.Add(e);

            if (++currentBatchSize % batchSize == 0)
            {                
                yield return batch;
                batch.Clear();
            }            
        }
        yield return batch;
    }
}

I'm sure you can find something like this in morelinq package.

Usage:

static void Print(List<int> list, int charactersPerLine)
{
    foreach (var batch in list.Batch(charactersPerLine)) 
    {
        var strBatch = batch.Select(e => e.ToString()).ToArray();
        Console.WriteLine(string.Join(",", strBatch));
    }
}

Upvotes: 0

Felix Castor
Felix Castor

Reputation: 1675

You could use String Builder first. Then just put a \n after each line.

StringBuilder str = new StringBuilder();
int count = 1;

foreach (int i in List)
{

     str.Append(i.ToString());

     if(count%4 ==0)
        str.Append("\n");
     count++;
} 

Console.Write(str.ToString());

Upvotes: 1

Jaroslav Kadlec
Jaroslav Kadlec

Reputation: 2543

Use:

foreach (int i in List)
{
    Console.WriteLine("{0}", i);
}

If your input is in {1,2,3,4,5,6,7,8} format you have to use some condition when to use Console.WriteLine() or Console.Write()

const int LineCharacterLimit = 4;

int i = 0;    
foreach (int i in List)
{
   i++;
   if (i == LineCharacterLimit)
   {
      Console.WriteLine("{0}", i);
      i=0;
   }
   else 
   {
      Console.Write("{0}", i);
   } 
}

Upvotes: 3

Related Questions