Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to remove any value that is a duplicate

Tags:

c#

linq

I've seen this question on SO but it doesn't answer my question because I want to remove all instances of a value that is also a duplicate.

For example if I have a list with these values: A, A, C, D, B, A, E, E

I want to write some logic where the new list has these values: C, D, B.

Because A and E are classed as duplicates I want to remove them completely.

So with that in mind this is my code:

// List having duplicate string elements.
List<string> list = new List<string>();
list.Add("A");
list.Add("A");
list.Add("C");
list.Add("D");
list.Add("B");
list.Add("A");
list.Add("E");
list.Add("E");

// Get distinct elements.
var distinct = (from item in list orderby item select item).Distinct();

foreach (string value in distinct)
{
    Console.WriteLine("Distinct : {0}", value);
}

And this is the output:

A, B, C, D, E

like image 439
nick gowdy Avatar asked Jan 03 '14 15:01

nick gowdy


People also ask

Does Linq Union remove duplicates?

Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.

How do you remove the row containing the identical transactions?

Click on the data tab at the top of the screen Once you have selected the range, check the top of the screen and click the data tab. The different commands will be shown, and you should then check for 'remove duplicates' and click on it.


1 Answers

This should do it (C should be in the the list too, it only appears once in the code example)

var distinct = list.GroupBy(x=>x).Where(y=>y.Count()==1).Select(z=>z.Key);
like image 52
Original10 Avatar answered Nov 03 '22 23:11

Original10