Seeloewen
Seeloewen

Reputation: 15

Find duplicates in a string array in VB.Net

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.

Upvotes: 0

Views: 701

Answers (3)

dbasnett
dbasnett

Reputation: 11773

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

Upvotes: 1

G3nt_M3caj
G3nt_M3caj

Reputation: 2705

This might help you:

Dim duplicates As List(Of String) = WithDuplicates.Distinct.Where(Function(el) Array.IndexOf(WithDuplicates, el) <> Array.LastIndexOf(WithDuplicates, el)).ToList

Upvotes: 2

djv
djv

Reputation: 15782

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

Upvotes: 1

Related Questions