Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

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?

like image 794
MetaGuru Avatar asked Oct 27 '10 20:10

MetaGuru


People also ask

What method do you use to remove an item from a list t at a specific index?

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.


2 Answers

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.

like image 86
Ani Avatar answered Oct 06 '22 04:10

Ani


Like this:

list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID));
like image 33
SLaks Avatar answered Oct 06 '22 02:10

SLaks