简体   繁体   English

从 linq 列表中删除多索引

[英]Remove multi indexes from linq list

I want to remove multiple indexes from a linq list, I am using the following code:我想从 linq 列表中删除多个索引,我使用以下代码:

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.列表中有 3 个元素,现在我想要的是 select 只有第一个和第三个元素,然后执行 ForEach 以删除它们。

[Edit] [编辑]

The Problem is also that Indexes are dynamic.问题还在于索引是动态的。

    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 如果您的列表( toRemove )很大,您可以通过更改toRemove的声明,将搜索时间( 包含 )从O(n)减少到O(1)

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

Generally, you can use indexed overload of Where filter to select items at multiple indexes. 通常,您可以使用Where过滤器的索引重载来选择多个索引处的项目。 Keep in mind that LINQ only gives you a view of the collection - another collection instance - so you cannot modify the original collection. 请记住,LINQ只为您提供集合的视图 - 另一个集合实例 - 因此您无法修改原始集合。 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. 如果Remove方法处理从其所有者中删除项目,则可能是这种情况,但这将是一种非常特殊且罕见的情况。

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. 但是为了能够删除项目,您可能需要在Descendants集合本身上调用某种Remove方法,或者您的方案中可能需要完全不同的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM