c# - How to remove matching items from a list using Linq or otherwise

Viewed 359

I'm trying to remove matching items from a list, which seems like a pretty simple task, but as luck would have it, I can't figure it out.

Example list:

List<int> points1 = new List<int>
{
    1, 2, 3, 3
};

I'm trying to get uniquePoints1 to be 1,2

I know there is .Distinct() but that would return 1,2,3 which is not what I want.

I've also tried the following along with .Distinct() but I get a red line saying Comparison made to the same variable, did you mean to compare to something else?

List<int> uniquePoints1 = points1.Where(x => x == x);
List<int> uniquePoints1 = points1.RemoveAll(x => x == x);

Any help or direction is appreciated.

2 Answers

You can use the GroupBy method to group the items, and then return only the numbers from groups that have a count of 1:

List<int> uniquePoints = points
    .GroupBy(x => x)              // Group all the numbers
    .Where(g => g.Count() == 1)   // Filter on only groups that have one item
    .Select(g => g.Key)           // Return the group's key (which is the number)
    .ToList();

// uniquePoints = { 1, 2 }

"Group by" to the rescue!

This is a LINQ variant -- see other answers for a non-LINQ version

var nonDuplicatedPoints = from p in points1
                          group p by p into g 
                          where g.Count() == 1
                          select g.Key;
Related