简体   繁体   English

从数组 c# 输出一定数量的元素

[英]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?我该怎么做,比如说在控制台上每行输出一个数组的 3 个元素? And doing this for the whole array?并对整个阵列执行此操作? Is there anything like the Java Scanner that could help me?有没有像 Java Scanner 这样的东西可以帮助我?

One way to do this would be with a for loop.一种方法是使用 for 循环。 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;这将要求您的数组的长度为 3 的倍数; 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.如果不是这种情况,您需要添加某种逻辑检查input[i + 1]input[i + 2]存在于数组中。

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:arrayElements作为输入,然后您可以将它们分组为指定大小的块,并从每个组中收集值并显示它:

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("");      
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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