c# - 如何删除一个 int 数组中存在于另一个 int 数组中的所有元素?

标签 c# arrays

在我的 C# 程序中,我有一个 int 数组,其中包含一组整数,并且偶尔会包含这些整数的重复项。我想创建一个数组,该数组仅包含初始数组中作为重复项存在的数字,但其本身不包含重复项。根据我对 C# 的新手理解,我认为以下代码可以解决问题:

int a = 9;
int b = 6;
int c = 3;
int index = 0;

int[] mltpls = new int[a + b + c];

while (a > 0)
{
    mltpls[index] = 2 * a;
    a -= 1;
    index += 1;
}

while(b > 0)
{
    mltpls[index] = 3 * b;
    b -= 1;
    index += 1;
}

while(c > 0)
{
    mltpls[index] = 5 * c;
    c -= 1;
    index += 1;
}

int[] mltpls_unique = mltpls.Distinct().ToArray();
int[] mltpls_dplcts = mltpls.Except(mltpls_unique).ToArray();

Console.WriteLine(mltpls_dplcts);

//EDIT

//By running the following code I can write out all numbers in "mltpls"
for (int i = 0; i < mltpls.Length; i++)
{
 Console.Write(mltpls[i] + ", ");
}

/*If I try to run equivalent code for the "mltpls_dplcts" array nothing
only a blank line is displayed.*/

当我运行这个目标时,我的控制台应用程序的最终结果是一个空白行。我对此的解释是数组 mltpls_dplcts 为空,或者我错误地打印了该数组。

如何从数组中只获取重复值?

最佳答案

My interpretation of this is that the array mltpls_dplcts is empty or that I'm incorrectly going about printing the array.

两种解释都是正确的

Distinct 将返回 mltps 中至少出现过一次的每个项目。如果您现在应用 Except,您将一无所获,因为 mltpls_unique 中的所有项目也都存在于 mltps 中。数组中的项目按值进行比较,因此对于 Except 来说,一个数字是否在另一个数组中出现多次并不重要。如果存在一次,则不会返回该号码。所以你得到一个空数组。

此外,您不能简单地将整个数组插入 Console.WriteLine 中。使用循环或 String.Join 来打印内容:

Console.WriteLine(String.Join(" ",mltpls_dplcts));

解决方案:您可以使用良好的旧循环方法来解决它;)

int[] mltpls_unique = mltpls.Distinct().ToArray();
// The amount of duplicates is the difference between the original and the unique array
int[] mltpls_dplcts = new int[mltpls.Length-mltpls_unique.Length];


int dupCount = 0;
for (int i = 0; i < mltpls.Length; i++)
{
    for (int j = i+1; j < mltpls.Length; j++)
    {
        if (mltpls[i] == mltpls[j])
        {
            mltpls_dplcts[dupCount] = mltpls[i];
            dupCount++;
        }
    }
}

Output: 18 12 10 6 15

关于c# - 如何删除一个 int 数组中存在于另一个 int 数组中的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47787660/

相关文章:

c# - SqlDataAdapter 不删除记录

c# - 使用 Unity Photon 将玩家位置发送给另一个玩家以在多人游戏中移动他

PHP - MySql 数组

将数组的元素复制到 C 中的链表

javascript - 操作 Javascript 对象数组

c++ - 错误 : Deallocating a 2D array

c# - 编译器接受抛出 NullReferenceException 的几乎对象初始化器

c# - 限制同时执行任务的数量

c# - 从列表中删除具有重复属性的对象

c# - 有没有一种方法可以更改命令前缀而无需重新启动机器人以使更改生效? (DSharpPlus)