可以说我有这个数组
int[] numbers = {1, 3, 4, 9, 2};
如何通过“名称”删除元素?,让我们说4吗?
甚至ArrayList没有帮助删除?
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); }
如果要删除所有4实例而不需要知道索引:
LINQ:(. NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 }; int numToRemove = 4; numbers = numbers.Where(val => val != numToRemove).ToArray();
非LINQ:(. 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();
如果只想删除第一个实例:
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();
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示例。