I've come across multiple examples of getting duplicates, and removing them from array. How do I do the opposite, to only getting the duplicates and removing the rest of the elements. from what I've learned from these examples: How do I remove duplicates from a C# array?, remove duplicates from two string arrays c#, I came up with a code to do "double" operation.
Code workflow: There is this array numbers of int[10], and another array duplicates of int[n], where n is undeterminable/depends on numbers. From numbers, I first set duplicates to the actual non-duplicates version of numbers using .Distinct().toArray(). Then I essentially have to minus off duplicates from numbers, to get the actual duplicated values. But smh in that process, its stating that my duplicates array is nulled.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayEx4
{
internal class Program
{
static void Display(int[] x)
{
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
}
static void Main(string[] args)
{
int[] numbers = new int[10];
int[] duplicates = { };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Enter number " + (i + 1) + ": ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
duplicates = numbers.Distinct().ToArray();
duplicates = numbers.Except(duplicates).ToArray();
Console.WriteLine("\n\nProvided data:\n");
Display(numbers);
Console.WriteLine("\n\nDuplicates:");
Display(duplicates);
Console.WriteLine(Console.ReadLine());
}
}
}
Img:
What am I doing wrong? Any explanation would be awesome!