我的表单有两个不同的数组,如下所示:
int[] X = { 14, 19, 24, 28, 33 };
int[] Y = { 90, 131, 132, 150, 170 };
我可以使用以下方法从两个数组(相同的索引号)中删除一个值:
int maxValue = Y[0];
for (int i = 1; i < Y.Length; i++)
{
if (Y[i] > maxValue)
maxValue = Y[i]; // max value in the array.
}
if (maxValue < 100)
{
int indexY = IndexOfInt(Y, maxValue);
Y = Y.Except(new int[] { maxValue }).ToArray();
List<int> Z = X.ToList();
Z.RemoveAt(indexY);
X = Z.ToArray();
}
static int IndexOfInt(int[] arr, int value) //finds the index number
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == value)
{
return i;
}
}
return -1;
}
上面的代码返回:
int[] X = { 19, 24, 28, 33 };
int[] Y = { 131, 132, 150, 170 };
比方说,我该如何着手删除具有相同值的多个实例
int[] X = { 14, 19, 24, 28, 33 };
int[] Y = { 90, 90, 132, 150, 170 };
我猜它必须是 while
循环,但无法正确理解循环或概念。这不是要避免重复。它是关于删除所有 <100
的值.我想从 X
中删除小于 100 的值数组来自,例如:
int[] Y = { 90, 90, 132, 150, 170 };
应该是
int[] Y = { 132, 150, 170 };
因为我们要删除 X[0]
X[1]
我们必须删除 Y[0]
Y[1]
int[] X = { 24, 28, 33 };
因为我必须使用这个数组来创建一个 Chart
以我的形式。我希望这能解决 Why
的问题.
最佳答案
I'm trying to remove the instances of values which lower than 100 in Y and corresponding values which has same index number in X. i.e my code removes Y[0] and X[0]
以下代码获取Y
中小于100的所有元素的索引(减去X
中不存在的那些索引,假设对于X
比 Y
短),然后从 X
和 Y
中删除所有这些索引位置的元素:
var X = new List<int> { 14, 19, 24, 28, 33 };
var Y = new List<int> { 90, 90, 132, 150, 170 };
var indexes = Y.Select((element, index) => new {element, index})
.Where(item => item.element < 100
&& item.index < X.Count)
.Select(item => item.index)
.OrderByDescending(i => i)
.ToList();
foreach (var index in indexes)
{
X.RemoveAt(index);
Y.RemoveAt(index);
}
集合将以 { 24, 28, 33 } 和 { 132, 150, 170 } 结尾。
关于c# - 如何循环从同一个数组中删除一个值的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27021622/