There is a similar question posted, but I do not have the rep to ask a follow-up question in that thread :(
That question and solution is HERE.
If I have a Lis
I have two options for you, one that uses HashSet
and other Linq
.
Option 1:
Using HashSet
, loop through collection and insert if it not exist and remove if it exists.
HashSet hash = new HashSet();
foreach(var number in list)
{
if(!hash.Contains(number)) hash.Add(number);
else hash.Remove(number);
}
list = hash.ToList();
Option 2:
Simple Linq,
group the elements and filter whose count >1
.
var list= list.GroupBy(g=>g)
.Where(e=>e.Count()==1)
.Select(g=>g.Key)
.ToList();
There is big performance gain using HashSet
over Linq
, it is obvious, Linq
(in this case) require multiple iterations, where as HashSet
uses single iteration and provides LookUp (for adding/removing) with O(1)
access.
Elapsed Time (Using Linq): 8808 Ticks
Elapsed Time (Using HashSet): 51 Ticks
Working Demo