【发布时间】:2017-12-13 07:28:58
【问题描述】:
在我的 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 是空的,或者我错误地要打印数组。
如何只从数组中获取重复值?
【问题讨论】:
-
可以添加输入数组内容吗?从代码中很难估计该数组中的真正内容。
-
使用 List
比使用数组更好。 -
@PMF 名为“mltpls”的数组的数组输入为:18, 16, 14, 12, 10, 8, 6, 4, 2, 18, 15, 12, 9, 6, 3、15、10、5
-
"如何在 C# 中删除另一个 int 数组中存在的 int 数组中的所有元素?"这个问题具有误导性。如果您删除
mltpls中存在于mltpls_unique中的所有元素,则将它们全部删除!这实际上就是你所做的。但似乎您希望将重复项挑出到一个新数组中