VB.NET - 读取包含制表符分隔的整数/双精度的文本文件并将它们存储在数组中 [英] VB.NET - Reading a text file containing tab-separated integers/doubles and storing them in arrays

查看:28
本文介绍了VB.NET - 读取包含制表符分隔的整数/双精度的文本文件并将它们存储在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含制表符分隔的整数和双精度的文本文件,例如:

I have a text file containing tab-seperated integers and doubles, e.g.:

5[TAB]0.3[TAB]2.9[TAB]61[TAB]110
8[TAB]1.1[TAB]5.2[TAB]13[TAB]45
1[TAB]0.8[TAB]1.4[TAB]28[TAB]33
...

我需要的是一种在 VB.NET 中将每一行作为双数组访问的便捷方法 - 这样第一个数组将是 [5.0 0.3 2.9 61.0 110.0],第二个数组将是[8.0 1.1 5.2 13.0 45.0],依此类推...

What I need is a convenient way to access each line as a double array in VB.NET - so that the first array would be [5.0 0.3 2.9 61.0 110.0], the second array would be [8.0 1.1 5.2 13.0 45.0], and so on...

如何使用 StreamReader 完成此操作?

How can this be accomplished using the StreamReader?

推荐答案

如果可以使用列表列表而不是数组列表,您可以这样做:

If it's ok to use a list of lists instead of a list of arrays, you can just do this:

Private Function LoadFile(ByVal filePath As String) As List(Of List(Of Double))
    Dim records As New List(Of List(Of Double))()
    For Each line As String In File.ReadAllLines(filePath)
        Dim values As New List(Of Double)()
        For Each field As String In line.Split(New String() {ControlChars.Tab}, StringSplitOptions.None)
            values.Add(Double.Parse(field))
        Next
        records.Add(values)
    Next
    Return records
End Function

或者,如果它必须是一个数组列表,你可以这样做:

Or, if it must be a list of arrays, you could do this:

Private Function LoadFileToArrays(ByVal filePath As String) As List(Of Double())
    Dim records As New List(Of Double())()
    For Each line As String In File.ReadAllLines(filePath)
        Dim values As New List(Of Double)()
        For Each field As String In line.Split(New String() {ControlChars.Tab}, StringSplitOptions.None)
            values.Add(Double.Parse(field))
        Next
        records.Add(values.ToArray())
    Next
    Return records
End Function

如果你需要一个数组数组,你可以只返回 records.ToArray(),而不是,在最后一个例子中.我没有添加任何代码来处理无效或空字段值,因为在您的问题中不清楚您希望如何处理这些值.因此,您需要添加代码来适当地处理该问题,否则,在这种情况下,此代码将引发异常.

If you need an array of arrays, you could just return records.ToArray(), instead, in that last example. I did not add any code to handle invalid or empty field values, because it wasn't clear, in your question, how you would want to handle those. So, you'll want to add code to handle that appropriately, otherwise, this code will throw an exception in such cases.

这篇关于VB.NET - 读取包含制表符分隔的整数/双精度的文本文件并将它们存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆