假设我有这个数组,
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 框架 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,则需要参考非 LINQ 示例。