How to remove all objects from List<object> where object.variable exists at least once in any other object.variable2?

后端 未结 2 1399
青春惊慌失措
青春惊慌失措 2021-01-18 12:08

I have having trouble figure out how to write this code.

I have a list of items, the items all have an ID. There is also another value that we will call otherID. If

相关标签:
2条回答
  • 2021-01-18 12:29

    Like this:

    list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID));
    
    0 讨论(0)
  • 2021-01-18 12:30

    One way to do this would be a 2-stage process:

    1. Build up a set of Ids that must be removed.
    2. Remove items from the list whose Id's are present in the blacklist.

    This will require two passes of the list. Since adding to a HashSet / testing if it contains an item should be a constant-time operation, the entire operation should run in linear time.

    var idsToBeRemoved = new HashSet<int?>(list1.Select(item => item.otherID)
                                                .Where(otherId => otherId.HasValue));
    
    list1.RemoveAll(item => idsToBeRemoved.Contains(item.ID));
    

    EDIT: Updated Id's type to int? after clarification from the OP.

    0 讨论(0)
提交回复
热议问题