简体   繁体   English

如何从 array1 打印 item[0] 并完成 array2 的结果(与 item[1] 重复)

[英]How can I print item[0] from array1 and complete the result from array2 (repeated with item[1])

I have these arraies我有这些数组

string[] array1 = {"A","A","A","A", "B","B","C","C","C","D"};
int[] array2 = {1,2,3,4,5,6,7,8,9,10};

The expected output is:预期的 output 为:

A一个

  • 1 1
  • 2 2
  • 3 3
  • 4 4

B

  • 5 5
  • 6 6

and so on.....等等.....

I tried this我试过这个

string[] array1 = { "A", "A", "A", "A", "B", "B", "C", "C", "C", "D" };

int[] array2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

for (int x = 0; x < array1.Length; x++)
{
    if (array1[x] == array1[x == array1.Length-1? x : x + 1])
    {
        Console.WriteLine(array1[x]);
        Console.WriteLine(array2[x]);
    }
    else
    {
        continue;
    }

}
Console.ReadKey();

But doesn't work as expected.但没有按预期工作。

How about:怎么样:

for (int x = 0; x < array1.Length; x++)
{
    // display first letter and any letter different from previous one
    if (x == 0 || array1[x] != array1[x - 1])
    {
        Console.WriteLine(array1[x]);
    }
    // in all cases, write the number
    Console.WriteLine(array2[x]);
}

Note that when doing this, you should make sure that array1.Length == array2.Length or you might end up in trouble.请注意,这样做时,您应该确保array1.Length == array2.Length否则您可能会遇到麻烦。

Is this a homework assignment or a practical problem you need to solve?这是您需要解决的家庭作业还是实际问题? If the former, then your classwork may require a solution using only arrays and then the other answer is probably preferred.如果是前者,那么您的课堂作业可能需要仅使用 arrays 的解决方案,然后可能首选其他答案 But if this is a practical problem, then IMHO LINQ would be a better approach, being more expressive of what you actually want to do.但如果这是一个实际问题,那么恕我直言 LINQ 将是一种更好的方法,更能表达你真正想做的事情。

For example:例如:

string[] array1 = {"A","A","A","A", "B","B","C","C","C","D"};
int[] array2 = {1,2,3,4,5,6,7,8,9,10};
var groups = array1.Zip(array2, (x, y) => (Name: x, Value: y)).GroupBy(t => t.Name);

foreach (var group in groups)
{
    Console.WriteLine(group.Key);
    Console.WriteLine(string.Join(Environment.NewLine, group.Select(t => t.Value)));
}

The above reorganizes the data by combining the corresponding values from each array into a single tuple value, and then uses LINQ to group each value by the name.上面通过将每个数组中的对应值组合成单个元组值来重组数据,然后使用 LINQ 按名称对每个值进行分组。

Once this is done, outputting the information is as simple as displaying the key for each group, and then displaying all the values within each group.完成此操作后,输出信息就像显示每个组的键一样简单,然后显示每个组中的所有值。

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

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