删除 VB.Net 中的特定数组字符串

Delete specific array string in VB.Net

我怎样才能删除所有的字符串而不是什么都不写?因为 nothing 实际上意味着一条线什么都没有,但这条线存在。我希望它不再存在!

Dim textfile() As String = IO.File.ReadAllLines(My.Application.Info.DirectoryPath + ("\textfile.txt"))

For i As Integer = 0 To textfile.Count - 1
    If textfile(i).Length > 1 Then
        textfile(i) = Nothing 'here i want to delete
    End if
Next

您可以使用 LINQ 来 select 只有不为空的行:

Dim textfile = IO.File.ReadAllLines(IO.Path.Combine(My.Application.Info.DirectoryPath, "textfile.txt"))
Dim filteredTextFile = textfile.Where(Function(line) Not String.IsNullOrWhitespace(line)).ToArray()

Fiddle: https://dotnetfiddle.net/nUpjEH

根据此 If textfile(i).Length > 1 Then,您似乎只想保留短行。而你只将 nothing 设置为长

使用 LINQ 执行此操作

Dim onlyShortLines() as String = 
   textfile.Where(Func(x) x.Length = 1).Select(Func(x) x).ToArray()

您需要过滤掉空行,然后写入文件。接受的答案完成了第一部分,所以这里是完整的解决方案

Dim textFile = File.ReadAllLines("filename.txt")
Dim fixedLines = textFile.Where(Function(line) Not String.IsNullOrWhiteSpace(line))
File.WriteAllLines("filename.txt", fixedLines)

@HansPassant 在评论中指出这不是最有效的解决方案。这是使用 StreamReader / StreamWriter

的另一种方法
Dim lines As New List(Of String)()
Using sr As New StreamReader("filename.txt")
    While Not sr.EndOfStream
        Dim line = sr.ReadLine()
        If Not String.IsNullOrWhiteSpace(line) Then lines.Add(line)
    End While
End Using
Using sw As New StreamWriter("filename.txt")
    For Each line In lines
        sw.WriteLine(line)
    Next
End Using

但是,使用一个 1kb 文件~1000 行文件和一些空行,我的系统第一种方法大约需要 18 毫秒,第二种方法需要 18 毫秒(每个平均 1000 次)。所以至少在我的系统中,在这种情况下,没有太大区别。如果效率是一个问题,请参阅 https://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/ 进行进一步分析。