I'm trying to find duplicates in an array and put only the duplicates in an array. The code im using is the following
Dim duplicates As List(Of String) =
WithDuplicates.GroupBy(Function(n) n) _
.Where(Function(g) g.Count() > 1) _
.Select(Function(g) g.First) _
.ToList()
Dim DuplicatesOnly As String() = duplicates.ToArray
WithDuplicates is the Array that contains the duplicates. Before, I used a richtextbox instead of a array but I had to switch to an array because of threading. I don't know why my code isnt working anymore. Any ideas how I could get this working?
Edit: The code above does indeed work, another part of my code caused the error.
CodePudding user response:
This might help you:
Dim duplicates As List(Of String) = WithDuplicates.Distinct.Where(Function(el) Array.IndexOf(WithDuplicates, el) <> Array.LastIndexOf(WithDuplicates, el)).ToList
CodePudding user response:
You almost had it. You just need to select the key instead of the first.
Dim withDuplicates As New List(Of String) From {"a", "b", "c", "a", "c"}
Dim duplicates As List(Of String) =
withDuplicates.GroupBy(Function(n) n).
Where(Function(g) g.Count() > 1).
Select(Function(g) g.Key).ToList()
Dim DuplicatesOnly As String() = duplicates.ToArray
Console.WriteLine(String.Join(", ", DuplicatesOnly))
a, c
CodePudding user response:
Your code works if there are duplicates. Jimi's first comment may be pertinent, but your question lacks that detail.
Dim WithDuplicates As New List(Of String) From {"aa", "b", "c", "aa", "c", "AA", "c"}
' Dim WithDuplicates As New List(Of String) From {"aa", "b", "c"} ', "aa", "c", "AA", "c"}
Dim duplicates() As String
duplicates = WithDuplicates.GroupBy(Function(n) n).
Where(Function(g) g.Count() > 1).
Select(Function(g) g.First).ToArray