vb.net - 加载一个包含 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
解决方案
您可以使用以下命令将文件读入数组:
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()}")
但如果这是家庭作业,绝对不要交这个!
推荐阅读
- javascript - 同步多个 Promise,同时允许多次重试
- javascript - 数组被错误解释
- git - 如何获得两个 git 分支的工作集(不是提交)之间的差异
- sql - 获取提供日期之间的所有日期
- javascript - Javascript随机名称总是返回相同的项目
- c# - ASP.NET Core MVC 通配符路由无法使用与另一个正在运行的相同设置
- r - 使用 dplyr 执行一个简单的数据帧子集
- apache-kafka - 卡夫卡 - 创建卡夫卡消费者后的问题
- java - 如何从列表中获取项目并添加 EditText?
- selenium - Gmail 密码 - 我在 PAssword 中找不到 Xpath,代码已写入但密码不正确