【问题标题】:Using VB 2013, I'm having trouble sorting an array of strings on substrings within each string使用 VB 2013,我无法在每个字符串中的子字符串上对字符串数组进行排序
【发布时间】:2016-01-03 15:13:57
【问题描述】:

我认为这很简单,但由于某种原因它没有出现在我身上......

这是我目前的代码

Dim fileReader As New StreamReader(FOfileToProcess)
Dim sLine As String = ""
Dim fileText As New ArrayList()
Do Until fileReader.EndOfStream()
    sLine = fileReader.ReadLine()
    If Not sLine Is Nothing Then fileText.Add(sLine)
Loop
fileReader.Close()
fileText.Sort(20, 2, Nothing) 'My intention is to sort by the values at zero-based 20 for 2 characters
fileText.Sort(63, 9, Nothing) '... and likewise at zero-based 63 for 9 characters
Dim saText() As String = DirectCast(fileText.ToArray(GetType(String)), String())
File.WriteAllLines(FOfileToProcess + "_sorted", saText)

它可以工作,但是写出的“_sorted”文件没有正确排序。只是更正我的排序字段的问题吗?原始排序是 2 字段排序,主要是第 63 列,次要是第 20 列,但由于只有一组参数,我想先选择次要并以主要结尾。

建议?

TIA!

【问题讨论】:

  • 为什么你仍然使用过时的ArrayList 而不是List(Of String)
  • 我不需要使用arraylist;我可以使用任何东西。实际上,我已经有一段时间没有接触过 vb 程序了,而我正在努力更新的原始程序可能是在 VB5 中开始的。我没有时间将整个东西转换为 C#,所以我现在只需要留在 VB...
  • 酷!我将 ArrayList 更改为 List(of String) 和适当的排序范围,瞧!谢谢@TimSchmelter!非常感谢!
  • 那我误解了你的要求。但我很高兴它现在可以工作了。
  • 哎呀...我的错误:我在视觉上比较文件并将它们混淆了。排序工作不正常......我在下面尝试了你的答案,但没有 File.ReadLines 方法。有一个 ReadAllLines 方法,但它说它不可查询。

标签: vb.net sorting visual-studio-2013 arraylist


【解决方案1】:

首先,不要使用ArrayList,因为它不允许您指定项目的类型。相反,请使用List(Of T)

Dim fileText As New List(Of String)

其次,Sort 方法的索引与行号有关,而不是与字符串中的某个位置有关(ArrayList 不知道您在插入字符串)。

Dim fileTextSorted = fileText _
    .OrderBy(Function(s) s.Substring(20, 2)) _
    .ThenBy(Function(s) s.Substring(63, 29))

如果文件包含的行短于所需的子字符串位置或空行(例如,文件末尾有一个空行),则使用 VB 函数 Mid 优于 Substring 可能会抛出例外。或者,您可以通过首先应用Where 条件来丢弃这些行:.Where(Function(s) s.Length >= 72) _,或者在读取文件时不要将这些行添加到列表中。

【讨论】:

  • 我尝试了您的解决方案,但编译器无法将 OrderBy 或 ThenBy 识别为 List 的方法。我做错了吗?
  • 在代码顶部添加Imports System.Linq
  • 是的。在你发布它之前想通了。谢谢!
【解决方案2】:

ArrayList.Sort(Int32, Int32, IComparer) 不会按子字符串对字符串进行排序。您可以只指定要排序的范围,例如字符串 21 到 23 和 64 到 73。

您想按每个字符串中的子字符串排序。我可以使用 LINQ 和ReadLines/WriteAllLines 为您提供更易读的方法吗?

Dim lines = From line In System.IO.File.ReadLines(FOfileToProcess)
            Where line.Length >= 73
            Let col1 = line.Substring(20, 2)
            Let col2 = line.Substring(63, 9)
            Order By col1 Ascending, col2 Ascending
            Select line
System.IO.File.WriteAllLines(FOfileToProcess + "_sorted", lines)

【讨论】:

  • 想通了。 “导入 System.Linq”。呸!对此感到抱歉。
  • 我选择了 Olivier 的解决方案,因为我一直收到一个类型转换错误。我想这可能是我翻译错误的东西,但我非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2015-09-11
  • 2012-10-14
  • 1970-01-01
  • 2020-02-20
  • 2014-01-05
  • 1970-01-01
  • 2016-05-25
  • 2023-04-07
相关资源
最近更新 更多