0

I have the following array:

new string[] { "A", "B", "C", "D", "A" }

What I want to do is to remove the duplicated values and the value that is duplicated. I expect this result:

new string[] { "B", "C", "D" }

Im trying doing this:

names.Distinct().ToArray();

But this only remove the duplicated value and leaves the original in the array.

How can I solve it?

User1899289003
  • 850
  • 2
  • 21
  • 40

2 Answers2

3

If you're wanting to remove all the duplicate items, you can group by the value and select all items that have a count of 1.

For example:

var tmp = new string[] { "A", "B", "C", "D", "A" };
var unique = tmp.GroupBy(s => s) // Group all items into a collection
                .Where(s => s.Count() == 1) // Only select items that occur a single time
                .Select(s => s.Key); // Select the original value back out (stored as the Key).
foreach(var item in unique) {
    Console.WriteLine(item);    
}
JD Davis
  • 3,517
  • 4
  • 28
  • 61
  • 2
    This is good, but I'd add that there is a potential optimization if we're in a scenario where the number of duplicates is large. (That is, we have, say, a thousand "A" duplicates instead of two.) Instead of `.Where(s => s.Count() == 1)` you can say `.Where(s => s.Take(2).Count() == 1)` which means "start counting the items and if you get to two, discard it". The former, by contrast, means "start counting the items and *after you're done counting*, discard the ones that are not one". If you want to know if there are two or more pennies in a jar, you don't have to count all the pennies. – Eric Lippert Feb 11 '20 at 19:35
  • There are other ways to solve this problem as well; `!s.Skip(1).Any()` for example does the same thing, but I find it slightly harder to read. – Eric Lippert Feb 11 '20 at 19:37
  • 1
    @EricLippert thanks for the input. I hadn't actually considered the performance implications of that. – JD Davis Feb 11 '20 at 20:31
  • With the current implementation of ‘Enumerable.GroupBy’ ‘Enumerable.Count’ is likely the fastest approach. The grouping is cached and implements ‘ICollection.Count’. – Johnbot Feb 13 '20 at 12:13
-4

You cannot change the size of an array. However you could assign the array back to the variable.

names = names.Distinct().ToArray()

Update: Doh misread the question on my mobile.

Are you wanting to alter the array because the above answer about updating the variable still applies.

To get items that only occur once.

names.GroupBy(x => x).Where(x => !Skip(1).Any()).Select(x => x.Key).ToArray();
Bob Vale
  • 18,094
  • 1
  • 42
  • 49