简体   繁体   中英

C# LINQ Remove multiple objects from a list in single execution

It seems quite similar, but my question is quite different. I have a list which consists of objects which are implementation of different interface. I want to delete a particular type's objects, but after passing another criteria. A sample code is given below.

 // remove the not required parameters 
foreach (EndPoint endPoint in endPoints)
{                 
    var maps = endPoint.EndPointParameters
        .Where(x => x is IEndPointParamMapCustom)
        .Cast<IEndPointParamMapCustom>()
        .Where(x => !x.IsActive)
        .ToList();

    foreach (var custom in maps)
    {
        endPoint.EndPointParameters.Remove(custom);
    }
}

I want to remove the below foreach loop and remove the objects in the above single LINQ query. Is it possible? Thanks.

你可以使用RemoveRange函数endPoint.endPointParameters.RemoveRange(maps)

If EndPointParameters is a List<T> ("remove multiple objects from a list ") you can try RemoveAll instead of Linq :

// Remove the not required parameters 
foreach (EndPoint endPoint in endPoints)
{ 
    // Remove all items from EndPointParameters that both
    //   1. Implement IEndPointParamMapCustom 
    //   2. Not IsActive 
    endPoint
      .EndPointParameters                
      .RemoveAll(item => (item as IEndPointParamMapCustom)?.IsActive == false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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