我可以使用哈希表来存储字符串和整数的组合

时间:2016-05-09 00:07:21

标签: vb.net

如果我有如下文件:

C
D
E
A
A
B

我想存储所有字符串的重复

A 2
B 1
C 1
D 1
E 1

我通过定义自定义类开始使用Arrays,但我发现删除该数组中的项目很痛苦。我读到Hashtables非常灵活地添加/删除项目

Dim File1Reader As New System.IO.StreamReader(TextBox1.Text)
Dim lineCount1 = File.ReadAllLines(TextBox1.Text).Length

Dim File1line As String
Dim file1items(lineCount1) As String
Do While File1Reader.Peek() <> -1
    File1line = File1Reader.ReadLine
    If File1line.Length > 0 Then
        file1items(i) = File1line
    End If

    i = i + 1
Loop

System.Array.Sort(Of String)(file1items)

Dim file1table As New Hashtable()
Dim file1count As New Dictionary(Of String, Integer)()

For x = 0 To (lineCount1 - 2)

    If file1items(x) = file1items(x + 1) Then
        c = c + 1
    Else
        c = 1
    End If

    file1count.Add(file1items(x), c)
Next

    MsgBox(file1count(0))

我收到以下错误:

  

未处理的类型&#39; System.ArgumentNullException&#39;发生了   在mscorlib.dll中

     

附加信息:值不能为空。

如果存在此异常的处理程序,则可以安全地继续该程序。

1 个答案:

答案 0 :(得分:0)

你一定很难做到这一点。

Dim results As List(Of IGrouping(Of String, String)) =
         File.ReadLines(TextBox1.Text).
              GroupBy(Function(s) s.Trim()).
              OrderBy(Function(g) g.Key). 
              ToList()

MsgBox(String.Format("{0,-5}{1}",results(0).Key, results(0).Count()))

从问题中如何排序是不清楚的。如果您更关心计数而不是密钥,您可能需要使用以下代码。请注意添加Select() linq运算符,在这种情况下,通过避免重新计算组的需要来提高性能。此外,由于匿名类型,我不得不回退results变量的类型推断。

Dim results = File.ReadLines(TextBox1.Text).
              GroupBy(Function(s) s.Trim()).
              Select(Function(g) New With {.Key = g.Key, .Count = g.Count()}).
              OrderBy(Function(g) g.Count * -1).
              ThenBy(Function(g) g.Key).
              ToList()

MsgBox(String.Format("{0,-5}{1}",results(0).Key, results(0).Count))