如何从C#中的数组中删除元素
可以说我有这个数组
int[] numbers = {1, 3, 4, 9, 2};
如何通过“名称”删除元素?,让我们说4吗?
甚至ArrayList
没有帮助删除?
string strNumbers = " 1, 3, 4, 9, 2";ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' }));
numbers.RemoveAt(numbers.IndexOf(4));
foreach (var n in numbers)
{
Response.Write(n);
}
回答:
NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 };int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
NET Framework 2.0)
static bool isNotFour(int n){
return n != 4;
}
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();
NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2, 4 };int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
NET Framework 2.0)
int[] numbers = { 1, 3, 4, 9, 2, 4 };int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();
以防万一您还没有弄清楚,正如Malfist指出的那样,您需要针对.NET Framework
3.5,以使LINQ代码示例能够正常工作。如果目标是2.0,则需要参考Non-LINQ示例。
以上是 如何从C#中的数组中删除元素 的全部内容, 来源链接: utcz.com/qa/414686.html