0

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.

2
  • 1
    Do you want to get new Array as a result? Arrays are immutable, you only can set NULL instead of reference to an object Commented Jul 16, 2017 at 9:52
  • @opewix It's not enough for me just to set null, I need a new (smaller) array without the objects that their indexes are in "indexes". Commented Jul 16, 2017 at 9:56

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Is the order of the remained objects will be the same as before the deletion? Thank you.
@Ilan Yes, the input enumerable is processed in order.
1

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

1 Comment

@openwix Thanks.. The non-linq version is indeed quite simple. But I'd like to do the same thing using LINQ query. If it's possible, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.