- Home /
Remove all duplicates from a list
Feeling dumb, but I couldn't find an answer here or the forums.
I have a list of gameobjects and I want to remove all occurrences of a specific gameobject from that list. I've played around using RemoveAll() and ForEach loops, but no luck so far.
To illustrate my request:
List<GameObject> testList = new List<GameObject>();
testList.Add (obj1);
testList.Add (obj1);
testList.Add (obj2);
testList.Add (obj3);
What I would like to be able to do, for example, is to remove all occurrences of obj1 from testList. The testList should then only return obj2 and obj3.
While the Linq options are definitely the cleanest, its worth bearing in $$anonymous$$d that if you are building an iOS game some of the functions can break at runtime. I'm not sure which ones cause problems, but if you have trouble do check it out!
Answer by Huacanacha · Oct 30, 2013 at 05:02 AM
You should be able to use RemoveAll() like this:
list.RemoveAll(obj => obj == objToDelete);
It works for me in Unity... here's my sample console output:
> List<String> list = new List<String> {"a","b","b","c"};
> String.Join(",", list.ToArray());
a,b,b,c
> list.RemoveAll(obj => obj == "b");
2
> String.Join(",", list.ToArray());
a,c
Edit: updated to the corrected answer from the comments below.
That actually may not work. I'm trying to remove all occurrences of one object, not all duplicates of all objects. Unless I misunderstood how Distinct() works.
To elaborate:
If testList contains (obj1, obj1, obj2, obj2, obj3), I want to be able to remove all obj1 and leave me with (obj2, obj2, obj3). Is this possible?
Also, I am making an iOS project.
$$anonymous$$y apologies... I must have read the other answer more closely than your question!
You should be able to use RemoveAll() like this:
list.RemoveAll(obj => obj == objToDelete);
It works for me in Unity... here's my sample console output:
> List<String> list = new List<String> {"a","b","b","c"};
> String.Join(",", list.ToArray());
a,b,b,c
> list.RemoveAll(obj => obj == "b");
2
> String.Join(",", list.ToArray());
a,c
That's what I was looking for! You should convert your comment to an answer so I can accept it. Thanks a lot!