Arrays 查找、计数和索引数组中的重复项
我有一个数组,它有一些重复的值。Arrays 查找、计数和索引数组中的重复项,arrays,vb.net,arraylist,Arrays,Vb.net,Arraylist,我有一个数组,它有一些重复的值。 我必须计算每个重复项目的数量及其索引。 打印例如: Index of b: 1 Index of b: 4 Index of c: 2 Index of c: 3 Index of c: 5 Index of e: 7 Index of e: 8 Total duplicate b: 2 Total duplicate c: 3 Total duplicate e: 2 在我的代码中,我只能找到重复的值 Dim list As New List(Of Str
我必须计算每个重复项目的数量及其索引。
打印例如:
Index of b: 1
Index of b: 4
Index of c: 2
Index of c: 3
Index of c: 5
Index of e: 7
Index of e: 8
Total duplicate b: 2
Total duplicate c: 3
Total duplicate e: 2
在我的代码中,我只能找到重复的值
Dim list As New List(Of String) From {"a", "b", "c", "c", "b", "c", "d", "e", "e"}
Dim duplicates = list.GroupBy(Function(x) x).Where(Function(x) x.Count > 1).Select(Function(x) x.Key)
For Each i As String In list.ToArray
If duplicates.Contains(i) Then
Debug.WriteLine("Duplicate Element: " & i & "Index: " & list.IndexOf(i))
End If
Next
其输出:
Duplicate Element: bIndex: 1
Duplicate Element: cIndex: 2
Duplicate Element: cIndex: 2
Duplicate Element: bIndex: 1
Duplicate Element: cIndex: 2
Duplicate Element: eIndex: 7
Duplicate Element: eIndex: 7
方法
Dim list As New List(Of String) From {"a", "e", "e", "b", "c", "c", "b", "c", "d", "e"}
Dim duplicates As IEnumerable(Of String) = list.Distinct
duplicates = From s In duplicates
Where list.FindAll(Function(l) l = s).Count > 1
Select s
For Each s As String In duplicates
Dim ct As Integer = (From l In list Where l = s Select l).Count
Debug.WriteLine(s)
Debug.WriteLine("count:{0}", ct)
Dim idx As IEnumerable(Of Integer)
idx = From n In Enumerable.Range(0, list.Count)
Where list(n) = s
Select n Take ct
Debug.WriteLine("Indexes")
For Each n As Integer In idx
Debug.Write(n.ToString)
Debug.Write(" ")
Next
Debug.WriteLine("")
Next
输出
e
count:3
Indexes
1 2 9
b
count:2
Indexes
3 6
c
count:3
Indexes
4 5 7
你已经有了答案,但我提出了一个稍微不同的方法,它可能会在以后派上用场。这将使用与您已有的相同的LINQ方法 LINQ的查询创建一个对象,该对象包含
元素
列表中所有字符串的值和位置,对值进行分组,然后选择包含多个项目的组,最后按其键
值对组进行排序
Dim elements = {"a", "b", "c", "c", "b", "c", "d", "e", "e"}.ToList()
Dim duplicates = elements.Select(Function(elm, i) New With {.Value = elm, .Index = i}).
GroupBy(Function(obj) obj.Value).
Where(Function(grp) grp.Count() > 1).
OrderBy(Function(grp) grp.Key)
For Each group In duplicates
For Each dupe In group
Console.WriteLine($"Duplicate: {dupe.Value} Index = {dupe.Index}")
Next
Console.WriteLine($"Number of {group.Key} duplicates: {group.Count()}")
Next
这张照片是:
Duplicate: b Index = 1
Duplicate: b Index = 4
Number of b duplicates: 2
Duplicate: c Index = 2
Duplicate: c Index = 3
Duplicate: c Index = 5
Number of c duplicates: 3
Duplicate: e Index = 7
Duplicate: e Index = 8
Number of e duplicates: 2
太好了!谢谢。我也打算投稿,然后我意识到我的代码和这个答案没有任何区别。哈!@djv有一个可能有趣的替代方法:因为源代码是一个
列表
,所以可以在循环中使用BinarySearch,使用结果作为基本索引来搜索下一个值。这样会更有效率,甚至更短。你认为这是什么,工作面试?:)