简体   繁体   English

如何在vb.net中使用字典dataype

[英]How to use the dictionary dataype in vb.net

I am facing problems with this code, Can anyone suggest what are the problems with it, I am trying to find the frequency of each element in an array我正面临这段代码的问题,谁能建议它有什么问题,我试图找到数组中每个元素的频率

 Public Sub P3()
    Dim no, freq, arr(5) As Integer
    Dim dict As New Dictionary(Of Integer, Integer)()
    Console.WriteLine("Enter 5 Integer Elements : ")
    For i = 0 To 4
        arr(i) = Console.ReadLine()
    Next
    For i = 0 To 4
        no = arr(i)
        For j = 0 To 4
            If no = arr(i) Then
                freq += 1
            End If
        Next
        If dict.ContainsKey(no) Then
            dict(i) += 1
        End If
        freq = 0
    Next

    For Each ab As KeyValuePair(Of Integer, Integer) In dict
        Console.WriteLine("Frequency Of " & ab.Key, " is " & ab.Value)
    Next
End Sub

Here's your code little bit refactored:这是您稍微重构的代码:

Public Sub P3()
    Dim no, arr(5) As Integer
    Dim dict As New Dictionary(Of Integer, Integer)()
    Console.WriteLine("Enter 5 Integer Elements : ")
    For i = 0 To 4
        arr(i) = Console.ReadLine()
    Next
    For i = 0 To 4
        no = arr(i)
        If dict.ContainsKey(no) Then
            dict(no) += 1
        Else
            dict.Add(no, 1)
        End If
    Next

    For Each ab As KeyValuePair(Of Integer, Integer) In dict
        Console.WriteLine("Frequency Of " & ab.Key & " is " & ab.Value)
    Next
End Sub

This loop:这个循环:

For j = 0 To 4
    If no = arr(i) Then
        freq += 1
     End If
Next

is unnecessary, in outer loop we will count occurences (anyway, this way you might determine frequency, but you don't use it anyway, also you are counting it for every item separately, which is very, very inefficient).是不必要的,在外循环中我们将计算出现次数(无论如何,通过这种方式您可以确定频率,但无论如何您都不会使用它,而且您还单独为每个项目计算它,这是非常非常低效的)。

The problem with your dictionary was, that you weren't adding any elements to it!你的字典的问题是,你没有向它添加任何元素! Your if statement should look like:您的 if 语句应如下所示:

If dict.ContainsKey(no) Then
    dict(no) += 1
Else
    dict.Add(no, 1)
End If
Private Sub TestDic()
    Dim dic As New Dictionary(Of Integer, Integer) From
    {
        {1, 100},
        {2, 200},
        {3, 100},
        {4, 70},
        {5, 200},
        {6, 300}
    }
    Dim z = dic.GroupBy(Function(k) k.Value).
            Select(Function(w) New With {.Value = w.Key, .Count = w.Count()})
    '// Dump results to ListBox
    z.ToList().ForEach(Sub(x) lstResults.Items.Add($"Value: {x.Value}, Count = {x.Count}"))
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM