Remove array items with Array.FindAll
How can I remove an item in an array?
This is what I have, which is not OK.
// fr_watchdog.items = public array
string numToRemove = "test";
fr_watchdog.items = Array.FindAll(fr_watchdog.items,
val => val != numToRemove).ToArray();
All done. I have found a solution for this problem (listed below). Is it possible to delete the question?
ArrayList items = new ArrayList();
int index = Array.IndexOf(items, "Delete me");
if ( index != -1 )
{
string[] copyS开发者_开发问答trArr = new string[items.Length - 1];
for ( int i = 0; i < index; i++ )
{
copyStrArr[ i ] = items[ i ];
}
for ( int i = index ; i < copyStrArr.Length; i++ )
{
copyStrArr[ i ] = items[i + 1];
}
}
You can't "remove" an item from an array really - you can set an element's value to null (assuming it's a reference type) but arrays have a fixed size, so you can't "remove" an element any more than you can "add" one.
What you've shown in your question would create a new array - although it actually creates two arrays, because you're calling ToArray
on the result, for no particular reason.
It's not even clear which ToArray
method you're calling, given that you mentioned .NET 2, which doesn't include LINQ to Objects. Are you using LINQBridge? The more idiomatic LINQ way would be:
fr_watchdog.items = fr_watchdog.items.Where(val => val != numToRemove)
.ToArray();
However, you've said that that's "not ok" without saying in what way it's not okay. It will create a new array populated with items where the value isn't that of numToRemove
. In what way is that not what you want?
If the problem is just that the ToArray
method doesn't work precisely because you're using .NET 2 without LINQBridge, then just remove the call to ToArray()
from your original FindAll
code. Again, note that that won't change the contents of the existing array - so any other references to that original array will still see all the original items.
fr_watchdog.items
could be a read-only property (a property without a setter) or a read-only field (a field declared with the readonly
keyword). If that is the case, you cannot assign to it.
精彩评论