我认为这很简单,但是由于某种原因它没有出现在我身上...
到目前为止,这是我的代码
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列,但是由于只有1组参数,我想首先进行次要排序,然后以主要排序结束。
有什么建议吗?
TIA!
首先,请勿使用,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))
如果文件中包含比子字符串所需位置短的行或空行(例如,文件末尾的一个空行),则Mid
首选VB功能,Substring
而不是可能引发异常的功能。或者,您可以通过首先应用Where
条件来丢弃这样的行:.Where(Function(s) s.Length >= 72) _
或者在读取文件时不要将这样的行添加到列表中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句