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 otherID is zero or null, we will ignore it. However, if otherID contains the ID of another item in the list, I want to remove that item from the list.
Example:
item1.ID = 5, item1.otherID = null
item2.ID = 6, item2.otherID = 5
item3.ID = 7, item3.otherID = null
so item1 should be removed from the list because it's ID is present in the otherID field of item2
Any one know how I would write this?
RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.
One way to do this would be a 2-stage process:
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.
Like this:
list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With