# How to remove duplicate values from a list

I searched online for the answer but I just can’t seem to find a simple solution for my issue. I’m working on a grid based puzzle game and I can’t figure out how to handle multiple magnets magnetizing the same metal object. I calculate the empty space between the metal object and magnets and insert that value into a list. After a slight delay to make sure all magnets register, I want to remove all values with duplicates and find the smallest value from the remaining values. The LINQ Distinct().ToList() method doesn’t work, as it just removes the duplicates, but I want all values with duplicates to be removed from the list. I tried using multiple for loops and 2 lists that would cross check each other, but all that didn’t work either.

If you like LINQ then set your list to be equal to the list WHERE the COUNT of each value is 1:

``````list = list.Where(i => list.Count(j => i == j) == 1).ToList();
``````

This i == j check can be replaced by whatever equality check you need.

Then to get the smallest value from the remaining values, sort the values in ascending order then take the first:

``````list = list.OrderBy(i => i).ToList();
int smallest = list.FirstOrDefault();
``````

Again, replace “i => i” with whatever selector you use to determine what’s smallest, i.e. if you have a magnet class with a magnet power property you can use “i => i.MagnetPower” . Once you’re happy with these, you can daisy chain them to make a single call that just gets the smallest to prevent assigning all intermediary steps.

Hope this helps!

Sorry, but I’m quite new to coding (and LINQ), so I don’t understand what I’m supposed to do with that code. I have a list of ints that are the empty spaces in between all of the magnets trying to magnetize the object. Let’s say that list is “5, 4, 3, 5”. So if I use your code “emptySlotList= emptySlotsList.Where(i => emptySlotList.Count(j => i == j) == 1).ToList();”, I’m not quite sure how I’m supposed to replace the other values, so that I’m left with the values “4, 3”.