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

时间:2017-12-13 07:28:59

标签: 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是空的,或者我错误地打印数组。

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

5 个答案:

答案 0 :(得分:3)

  

我对此的解释是数组mltpls_dplcts为空或者我不正确地打印数组。

两种解释都是正确的

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++;
        }
    }
}
  

输出:18 12 10 6 15

答案 1 :(得分:1)

您无法直接打印数组。你需要逐个循环和打印:

foreach (var element in mltpls_dplcts)
{
    Console.WriteLine(element);
}

答案 2 :(得分:1)

您可以获得这样的不同重复数组:

var duplicates = mltpls.GroupBy(o => o)
    .Where(g => g.Count() > 1)
    .Select(g => g.First()).ToArray();

要获取新数组,该数组仅包含原始数组中不在第二个数组中的元素,您可以使用:

var newArr = mltpls.Except(duplicates).ToArray();

答案 3 :(得分:0)

查找重复项不是正确的方法。您可以使用GroupBy确定重复项,并将其打印到此控制台;

        var mltpls_dplcts = mltpls.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToArray();
        foreach (var duplicate in mltpls_dplcts)
        {
            Console.WriteLine(duplicate);
        }

此外,如果不必为您使用Array,建议您使用List<int>

答案 4 :(得分:0)

来自OP的更新问题:

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

var arr1 = new[] {1, 2, 4, 4, 5, 5, 5, 5, 6, 7, 1};
var duplicates = arr1.ToLookup(_ => _, _ => _).Where(_ => _.Count()>1).Select(_ => _.Key).ToArray();
// duplicates is now { 1, 4, 5 }

来自OP的原始问题:

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

var arr1 = new[] {1, 2, 4, 5, 6, 7};
var arr2 = new[] {4, 5};

var hash = new HashSet<int>(arr1);
hash.ExceptWith(arr2);
var filteredArray = hash.ToArray();

// filteredArray is now { 1, 2, 6, 7 }