Reputation: 999
I have an array of objects of type A:
A[] ar
.
And a list of integers:
List<int> indexes
.
How can I delete from the ar
all objects with indexes in the indexes
, using LINQ?
I.e. I need a new (smaller) array without the objects that their indexes are in indexes
. Using LINQ.
Is the order of the remained objects will be the same as before the deletion?
Thanks a lot.
Upvotes: 0
Views: 1514
Reputation: 108975
You cannot modify an array only the elements it contains.
But you can easily create a replacement array:
myArray = myArray.Where(x => x.KeepThisElement).ToArray();
With LINQ to Objects (which you'll be using in this case) there in an overload of Where
that passes the current index to the predicate:
myArray = myArray.Where((x, idx) => !indexes.Conatins(idx)).ToArray();
Upvotes: 2
Reputation: 5083
This may look odd, but it does what you want (it's not a LINQ):
var filtered = new List<A>();
for (var i = 0; i < ar.Length; i++)
{
if (indexes.Contains(i))
continue;
filtered.Add(ar[i]]);
}
var ar = filtered.ToArray();
If your integer list is very big, consider to use HashSet<int>
instead of list to get more performance
Upvotes: 1