首页 > 解决方案 > 加载一个包含 15 个数字的 .txt 文件,显示它们并删除重复的 VB.net

问题描述

正如标题所说,我还必须在它们旁边显示一个数字,此时该数字最初出现在文本文件中......所以如果一个数字出现在 .txt 文件的第一行并且该输出旁边的第十个应该显示为 1, 10.

到目前为止,这是我编写的代码。

即使用 c# 编写解决方案也会很有帮助,因为我可以转换它。

Imports System.IO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim FileReader As StreamReader
        Dim results As DialogResult
        Dim OpenFileDialog1 As New OpenFileDialog()
        results = OpenFileDialog1.ShowDialog

        If results = DialogResult.OK Then
            FileReader = New StreamReader(OpenFileDialog1.FileName)
            textBox1.Text = FileReader.ReadToEnd()
            FileReader.Close()

        End If

    End Sub
End Class

标签: vb.net

解决方案


您可以使用以下命令将文件读入数组:

Dim lines = IO.File.ReadAllLines("path")

您可以使用知道行号的 For 循环遍历数组:

For lineNumber = 0 To lines.Length-1

您可以创建一个Dictionary(Of String, Integer)将存储值和行号的值,但前提是该值以前从未见过:

Dim d as New Dictionary(Of String, Integer)

For ....

  Dim line = lines(lineNumber)
  If Not d.ContainsKey(line) Then d(line) = lineNumber + 1 ' plus one because arrays number from 0 but you seem to want first line numbered as 1

字典将在枚举循环的过程中填充唯一键和它们第一次看到的行号

您可以枚举字典并将其打印出来:

For Each kvp as KeyValuePair in d

  'if the file first line was "10 then
  Console.WriteLine(kvp.Key) 'prints e.g. "10" 
  Console.WriteLine(kvp.Value) 'prints e.g. 1 

我没有为你编写代码,因为它看起来真的像一个家庭作业,但试一试 - 你需要的一切都在这里


ps; 整个事情几乎可以使用 LINQ 在一行中完成。像:

IO.File.ReadAllLines(path) _
  .Select(Function(s,x) New With {.S = s, .X = x})
  .GroupBy(Function(w) w.S) _
  .Select(Function(g) $"{g.Key},{g.First()}")

但如果这是家庭作业,绝对不要交这个!


推荐阅读