1

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.

3
  • 1
    In general LINQ should never be used to modify objects but to query them Commented Jun 20, 2017 at 10:34
  • 1
    I guess it´s possible but the question is: why? YOur code is pretty straitforward, easy to understand and thus maintainable. Introducing any further LINQ will just mess your code up. Commented Jun 20, 2017 at 10:34
  • 1
    Given that the Q in LINQ stands for Query, you'll never perform this "single query" mutation without abusing the intent of LINQ. Commented Jun 20, 2017 at 10:35

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. but I asked to merge the both statements into one. not just to use removerange.
the syntax you provided gives a build error. it seems you didn't even check the code by yourself.
1

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

Comments

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.