问题描述
可以说我有这个数组,
INT []号= {1,3,4,9,2};
我怎样才能删除由名的元素? ,可以说数量4?
甚至的ArrayList
没有帮助删除?
字符串strNumbers =1,3,4,9,2;
ArrayList的数量=新的ArrayList(strNumbers.Split(新的char [] {','}));
numbers.RemoveAt(numbers.IndexOf(4));
的foreach(VAR N的数字)
{
回复于(N);
}
如果您要删除的4所有实例,而无需知道索引:的
LINQ:的(.NET Framework 3.5的)
INT []号= {1,3,4,9,2};
INT numToRemove = 4;
数= numbers.Where(VAL =>!VAL = numToRemove).ToArray();
非LINQ:的(.NET Framework 2.0中)
静态布尔isNotFour(INT N)
{
返回N = 4!;
}
INT []数= {1,3,4,9,2};
号码= Array.FindAll(数字,isNotFour).ToArray();
如果您要删除刚刚的第一个实例:的
LINQ:的(.NET Framework 3.5的)
INT []号= {1,3,4,9,2,4};
INT numToRemove = 4;
INT numIndex = Array.IndexOf(数字,numToRemove);
数= numbers.Where((VAL,IDX)=>!IDX = numIndex).ToArray();
非LINQ:的(.NET Framework 2.0中)
INT []号= {1,3,4,9,2,4};
INT numToRemove = 4;
INT numIdx = Array.IndexOf(数字,numToRemove);
名单< INT> TMP =新的名单,其中,INT>(数字);
tmp.RemoveAt(numIdx);
数= tmp.ToArray();
修改 以防万一你不是已经理解了它,因为Malfist指出的那样,你需要将目标定位在.NET Framework 3.5,以使LINQ code例子来工作。如果你目标定位2.0,你需要引用非LINQ的例子。
Lets say I have this array,
int[] numbers = {1, 3, 4, 9, 2};
How can I delete an element by "name"? , lets say number 4?
Even ArrayList
didn't help to delete?
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);
}
If you want to remove all instances of 4 without needing to know the index:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
Non-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();
If you want to remove just the first instance:
LINQ: (.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();
Non-LINQ: (.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();
Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.
这篇关于如何从C#中的数组删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!