Foyzul Karim
Foyzul Karim

Reputation: 4492

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.

Upvotes: 1

Views: 2056

Answers (2)

Mehang Rai
Mehang Rai

Reputation: 92

You can use the RemoveRange function endPoint.endPointParameters.RemoveRange(maps)

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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);
}

Upvotes: 1

Related Questions