DavidB
DavidB

Reputation: 2596

Removing items from a list with LINQ (removeAll)

I have two lists of objects, and I have been learning how to remove items from one list if they appear in another.

I have come up with this:

result.ResultantPoliciesTable.RemoveAll(item => result.PoliciesTable.Select
(f => f.PolicyName).Contains(item.PolicyName));

This works, but if an integer property of the object in ResultantPoliciesTable called ManagementID equals a value I will supply then I do not want this object to be removed.

Can anyone help me extend this query to achieve this?

Upvotes: 0

Views: 8146

Answers (2)

Patrick Stephansen
Patrick Stephansen

Reputation: 798

result.ResultantPoliciesTable
      .RemoveAll(item => 
                      result.PoliciesTable
                            .Where(i => i.ManagementID!=myId)
                            .Select(f => f.PolicyName)
                            .Contains(item.PolicyName)
                );

Upvotes: 0

w5l
w5l

Reputation: 5746

Try the following:

int doNotRemoveID = 7862384732;
result.ResultantPoliciesTable.RemoveAll(
    item => item.ManagementID != doNotRemoveID && 
            result.PoliciesTable.Select(f => f.PolicyName).Contains(item.PolicyName));

The variable item will be filled with each record from your ResultantPoliciesTable, and if your resulting method returns true, it will be removed. Thus, adding a check to see if item.ManagementID needs to be excluded should be enough to fit your needs.

Upvotes: 3

Related Questions