Quote:
what I am trying to do is take an input list from the user and checking if there are any duplicates in it and then print which elements are duplicates.
So basically My List1 is the user input and List2 is the List1.Distinct() (I am trying this by hardcoding just to understand how can I extract the duplicate values)
So basically if my input list is like: {1,2,3,4,2,1,5}
Output I am expecting is {1,2} since 1,2 have duplicate values
Here is a different approach:
List<int> list1 = new List<int>() { 1, 2, 3, 4, 2, 1, 5 };
List<int> duplicates = list1
.GroupBy(x => x)
.Where(x => x.Count() > 1)
.Select(x => x.Key)
.ToList();
Console.WriteLine(string.Join(',', duplicates));
Output:
1,2
What it does is
1. generate a grouping of unique values, with all of the same values
2. then use the count to identify duplicates
3. only select those duplicates
4. output the results as a list of integers
The last line joins all the results and outputs to the console.