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
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With