Home > database >  C# Split a List in Columns
C# Split a List in Columns

Time:02-08

I am trying to split a List in C# and display the results in columns like this:

ID 1  ID 2
ID 3  ID 4
ID 5  ID 6

Instead of displaying them like this:

ID 1
ID 2
ID 3
ID 4
ID 5
ID 6

This is my list:

private List<ID> IDs = new List<ID>();

And I'm trying to do something like this:

int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 8).Chunk(3))
{
    Console.WriteLine($"Chunk {chunkNumber  }:");
    foreach (int item in chunk)
    {
        Console.WriteLine($"    {item}");
    }

    Console.WriteLine();
}

Any help on how to accomplish this? Thanks

CodePudding user response:

just use Write instead of WriteLine

foreach (int item in chunk)
{
    Console.Write($"    {item}");
}

or this if you like it more

Console.Write($"    ID {item}");

CodePudding user response:

You can index by steps of 2 with a for-loop

for (int i = 0; i < IDs.Count; i  = 2)
{
    Console.WriteLine($"{IDs[i]}  {IDs[i 1]}");
}

This will only work if the list has an even number of elements. To be able to handle odd-length lists, try something like this

for (int i = 0; i < IDs.Count; i  = 2)
{
    if (i < IDs.Count - 1)
        Console.WriteLine($"{IDs[i]}  {IDs[i 1]}");
    else
        Console.WriteLine($"{IDs[i]}");
}
  •  Tags:  
  • Related