如:
P01, A ,2
P01, A ,3
P01, B ,1
P01, B ,4
P02, A ,6
P02, B ,7
P02,C ,2
P02,C ,1
想得到:
1,2列相同时,3列的值求和 ,如:第1,2行 2+3,第3,4行 1+4,第5行 6,第6行 7,第7,8行 2+1
------解决思路----------------------
边读边计算的如果用计数器则可以指定读取第几行内容第一例
Dim 文件路径 As String = System.Environment.CurrentDirectory + "\新建文本文档.txt"
Dim 内容 As New List(Of String), 暂存 As String = ",,1", 计算 As String()
If New FileInfo(文件路径).Exists Then
Dim 打开 As New FileStream(文件路径, FileMode.Open)
Dim 读取 As New StreamReader(打开)
Dim 判断 = 0
While (读取.EndOfStream <> True)
Dim 取值 = 读取.ReadLine()
判断 += 1
If (暂存.Split(",")(0) <> 取值.Split(",")(0)) Or (暂存.Split(",")(1) <> 取值.Split(",")(1)) Then
If 判断 > 1 Then
内容.Add(暂存)
End If
暂存 = 取值
Else
计算 = 取值.Split(",")
计算(2) = (Int16.Parse(计算(2)) + Int16.Parse(暂存.Split(",")(2))).ToString
内容.Add(String.Join(",", 计算))
判断 = 0
End If
End While
End If
------解决思路----------------------
或者这样写更容易理解
Imports System.IO
Module Module1
Sub Main()
Dim result = From ln In File.ReadAllLines("data.txt") _
Let datas = ln.Split(","c)
Let key = datas(0).Trim + "," + datas(1).Trim
Group datas By key = key Into g = Group _
Select New With {.key = key, .Sum = g.Sum(Function(x) Integer.Parse(x(2)))}
For Each r In result
Console.WriteLine("{0} = {1}", r.key, r.Sum)
Next
Console.WriteLine("....press any key")
Console.ReadKey()
End Sub
End Module