我有一个Person类的objectList,它有一个Name属性。我的目标是最终得到一个唯一的名单。任何重复项都必须添加一个数字。
例如,假设我们循环的对象具有如下名称:
John,Mike,Pete,Mark,Pete,Adam,Stan,Pete
我的独特清单应该看起来像:
John,Mike,Pete,Mark,Pete02,Adam,Stan,Pete03
我正在尝试执行以下操作,但Pete第三次进入后将无法正常工作:
Dim nameList As List(Of String)
Dim uniqueList As List(Of String)
For Each object In objectList
Dim name = object.Name
If nameList.Any(Function(str) str = name) Then
name = name + "02"
End If
nameList.Add(object.Name)
uniqueList.Add(name)
Next
答案 0 :(得分:1)
尝试替换
name = name + "02"
带
name = name & (uniqueList.Count(Function(str) str Like name & "*") + 1).ToString()
后者计算uniqueList中Pete *(= Pete,Pete02等)的出现次数,因此知道要追加的数字。请注意:如果你有例如"帕姆"和" Pamela"在列表中,下一个Pam将获得3号作为" Pamela"以" Pam"开头同样。
答案 1 :(得分:1)
使用LINQ:
Dim namesList = New String() {"Pete", "Mary", "Pete", "Pete"}
Dim namesListUnique = namesList.Select(Function(item, index) New With { _
.OriginalName = item, _
.Index = index _
}).Select(
Function(item)
Dim nbBefore = namesList.Take(item.Index).Count(Function(i) i = item.OriginalName)
Dim uniqueName = item.OriginalName
If nbBefore > 0 Then
uniqueName &= (nbBefore + 1).ToString("00")
End If
Return uniqueName
End Function _
).ToList()
答案 2 :(得分:1)
试试这个: -
Dim result = names.GroupBy(Function(x) x) _
.SelectMany(Function(x) x.[Select](Function(v, i) New With { _
Key .Value = v, Key .Index = i}) _
.Select(Function(z) z.Value + (If(z.Index <> 0,
(z.Index + 1).ToString(), [String].Empty))))
C#
相当于: -
var result = names.GroupBy(x => x)
.SelectMany(x => x.Select((v,i) => new { Value = v, Index = i })
.Select(z => z.Value + (z.Index != 0 ? (z.Index+1).ToString()
: String.Empty)));
答案 3 :(得分:1)
我只想用字典存储号码。
Dim namesList = New String() {"John", "Mike", "Pete", "Mark", "Pete", "Adam", "Stan", "Pete"}
Dim uniqueList As New Dictionary(Of String, Integer)
For Each name As String In namesList
Dim uniqueName As String
uniqueName = name
If Not uniqueList.ContainsKey(name) Then
uniqueList.Add(name, 1)
Else
uniqueList(name) += 1
uniqueName &= uniqueList(name).ToString("00")
End If
Console.WriteLine(uniqueName)
Next