Ali
Ali

Reputation: 1678

Remove multi indexes from linq list

I want to remove multiple indexes from a linq list, I am using the following code:

slidePart
         .Slide
         .Descendants<DocumentFormat.OpenXml.Presentation.Picture>()
         .ToList()
         .ForEach(pic => pic.Remove());

There are 3 elements in the List and now what I want is to select only the 1st and 3rd element then execute ForEach to remove them.

[Edit]

The Problem is also that Indexes are dynamic.

Upvotes: 1

Views: 1702

Answers (3)

jptrujillol
jptrujillol

Reputation: 1

 slidepart 
.RemoveAll(x => toRemove.Contains(slidepart.IndexOf(x))).ToList();

Upvotes: -1

L.B
L.B

Reputation: 116168

    var toRemove = new int[] { 1,2,.... };

    slidePart.Slide
        .Descendants<DocumentFormat.OpenXml.Presentation.Picture>()
        .Where((x, i) => toRemove.Contains(i) )
        .ToList()
        .ForEach(pic => pic.Remove());

If your list (toRemove) is large, you may reduce the search time (of Contains) from O(n) to O(1) by changing the declaration of toRemove a little bit

var toRemove = new HashSet<int>(new int[] { 1 });

Upvotes: 3

Honza Brestan
Honza Brestan

Reputation: 10957

Generally, you can use indexed overload of Where filter to select items at multiple indexes. Keep in mind that LINQ only gives you a view of the collection - another collection instance - so you cannot modify the original collection. It may be possible if the Remove method handles removing an item from its owner, but that would be a very special and rare case.

In your case, getting the items would look like this

var toRemove = new[] { 1, 2, ... };

var itemsToBeRemoved = slidePart.Slide
    .Descendants<DocumentFormat.OpenXml.Presentation.Picture>()
    .Where((pic, index) => toRemove.Contains(index))
    .ToList();

But to be able to remove the items, you may need to call some sort of Remove method on the Descendants collection itself or there may be completely different approach needed in your scenario.

Upvotes: 0

Related Questions