Find and change duplicates in an array

I would appreciate your help when it comes to finding duplicates in a string.

Imagine that I have an array that looks like this:

apple; apple; banana; orange; kiwi; apple

Then I want to find all duplicates and put, for example, a 1 in front of the first duplicate and then a 2 on the next one, etc.

Like this: apple1;apple2;banana;orange;kiwi;apple3

I have tried different loops but nothing has worked well, have also tried this which ppr has answered in a question.

image

But did not get it to work satisfactorily.

If anyone has a Lambda expression that would work, I would be extremely grateful.

Regards Mike

@MiXs,

Welcome Back!

Try something similar to this, this is for a list, so you can try by converting your array into a list.

listx.[Select](Function(s, i) New With {Key
    .orgstr = s, Key
    .index = i
}).GroupBy(Function(x) x.orgstr).SelectMany(Function(g) g.[Select](Function(x, j) New With {Key
    .item = x, Key
    .suffix = j + 1, Key
    .count = g.Count()
})).OrderBy(Function(x) x.item.index).[Select](Function(x) If(x.count = 1, x.item.orgstr, x.item.orgstr & "_" + x.suffix)).ToList()

Hi @MiXs

inputStr = "apple; apple; banana; orange; kiwi; apple"
words = inputStr.Split(";"c)
wordCounts As New Dictionary(Of String, Integer)
result As New List(Of String)
For Each word In words
    Dim trimmedWord As String = word.Trim()
    If Not wordCounts.ContainsKey(trimmedWord) Then
        wordCounts(trimmedWord) = 1
        result.Add(trimmedWord)
    Else
        wordCounts(trimmedWord) += 1
        result.Add(trimmedWord & wordCounts(trimmedWord).ToString())
    End If
Next

At the end of For Each you can print this using Log Message or Message Box
Dim finalStr As String = String.Join(“;”, result)


Hope it helps!

Thank you so much @sarathi125

I get that:
With Option Strict On, implicit conversions from String to Double are not allowed.

Where am I doing wrong?

Regards Mike

I think i solved it, i added a .ToString to this part:
item.orgstr & “_” + x.suffix.ToString)).ToList() :slight_smile:

1 Like

Thank you so much @sarathi125 it worked perfectly :slightly_smiling_face:

@Parvathy thanks so much for your input, really appreciated! :slightly_smiling_face:

Regards Mike

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.