C#从锯齿状数组中删除重复项

标签 c# arrays duplicates

我正在为大学编写算法。除了最后一件事,我几乎拥有一切。 我现在有锯齿状的数字数组,这个数组的例子:

[0][1]
[1][11,12]
[2][3,7,11,15]
[3][6,7,10,11]

我需要删除重复项,例如删除所有下一行中存在于上一行中的每个数字。 输出应该是这样的:

[0][1]
[1][11,12]
[2][3,7,15]
[3][6,10]

我试过这样的:

for (int i = 0; i <= numbers.Length + 1; i++)
{
    int size = numbers[i].Length;
    for (int j = 0; j < size; j++)
    {
        if (numbers[i][numbers[i].Length] != numbers[i + 1][numbers[i + 1].Length])
        {
            newNumbers[i][j] = numbers[i][j];
        }
    }
}

但它没有按应有的方式工作。

最佳答案

您可以使用 Except 解决它System.Linq 命名空间中的方法。

在每次循环迭代中,遍历所有下一行并获取这些行与当前行之间的差异并将其重新分配回去。这是可能的,因为 jagged array是一个数组,其元素是数组,所有项都具有相同的 int 数据类型

int[][] jaggedArray = new int[4][];

jaggedArray[0] = new[] { 1 };
jaggedArray[1] = new[] { 11, 12 };
jaggedArray[2] = new[] { 3, 7, 11, 15 };
jaggedArray[3] = new[] { 6, 7, 10, 11 };

for (int i = 0; i < jaggedArray.Length; i++)
{
    var currentRow = jaggedArray[i];
    for (int j = i + 1; j < jaggedArray.Length; j++)
    {
        var result = jaggedArray[j].Except(currentRow);
        jaggedArray[j] = result.ToArray();
    }
}

如果打印结果数组

foreach (var array in jaggedArray)
{
    foreach (var item in array) 
        Console.Write($"{item} ");

    Console.WriteLine();
}

输出如下

result

关于C#从锯齿状数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702505/

相关文章:

c# - 列出 Entity Framework 中外键指向的实体

c# - EventLog.EntryWritten 事件处理过去的事件

c# - 为什么 MessageBox 不是 TopMost?

c++ - 允许在单链表 C++ 的合并排序中重复

php - 检查重复的电子邮件地址但排除当前用户

php - 复制php资源

c# - 如何在DynamicMethod中调用DynamicMethod

c++ - std::tuple 与 std::array 作为 std::vector 的项目

javascript - 将 postgresQL 中的时间戳附加到数组时间戳列

c++数组打印十六进制?