简体   繁体   中英

Outputting certain number of elements from array c#

How could I go about, lets say for example outputting 3 elements of an array per line on the console? And doing this for the whole array? Is there anything like the Java Scanner that could help me?

One way to do this would be with a for loop. You could use something like the following:

// input already defined as array
for (int i = 0; i < input.Length; i += 3) {
    Console.WriteLine(input[i] + ' ' + input[i + 1] + ' ' + input [i + 2]);
}

This would require that your array had a length that was a multiple of three; if this wasn't the case, you'd need to add some sort of logic checking that input[i + 1] and input[i + 2] existed within the array.

A possible, albeit somewhat verbose solution, would be like so:

for (int i = 0; i < input.Length; i += 3) {
  if (i + 2 >= input.length) {
      Console.WriteLine(input[i] + ' ' + input[i + 1] + ' ' + input[i + 2]);
  } else if (input[i + 1] >= input.length) {
      Console.WriteLine(input[i] + ' ' + input[i + 1]);
  } else {
      Console.WriteLine(input[i]);
  }
}

Linq solution:

  int[] data = Enumerable.Range(1, 20).ToArray();

  int groupSize = 3;

  var result = Enumerable
    .Range(0, data.Length / groupSize + 
             (data.Length % groupSize == 0 ? 0 : 1))
    .Select(index => data.Skip(index * groupSize).Take(groupSize))
    .Select(items => string.Join(", ", items));

  Console.Write(string.Join(Environment.NewLine, result));

Output:

1, 2, 3
4, 5, 6
7, 8, 9
10, 11, 12
13, 14, 15
16, 17, 18
19, 20

Let arrayElements be the input, then you can group them into chunks of specified size and collect values from each groups and display it:

List<int> arrayElements = new List<int>() { 1,5,2,3,6,4,87,96,54,5,4,5,6,2,5,9,5,5,5,6,2,45,6};

int chunkSize = 3;
var results = arrayElements.Select((x, i) => new { Key = i / chunkSize , Value = x })
                           .GroupBy(x => x.Key, x => x.Value)
                           .Select(x=>String.Join("  ",x.ToList()))
                           .ToList();

foreach (string chunk in results)
{
    Console.WriteLine(chunk);
}

Working Example

You can do some thing like this. It will print elements in a single line and will go to new line after printing three elements in a row.

    for(int i=0; i<arr.Length; ++i) {
        Console.Write(arr[i]+" ");

        if((i+1)%3==0){
            Console.WriteLine("");      
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM