VB.NET StreamWriter分组学生数据时出现行重复问题求助
VB.NET分组SQL学生数据写入TXT重复问题修复
问题根源
你遇到的每行数据重复问题,大概率是分组后错误遍历了整个DataTable的所有行,而非当前分组下的学生数据,导致每个分组都重复输出所有学生记录。
修正后的完整代码
Imports System.Data.SqlClient Imports System.IO Imports System.Linq Sub WriteGroupedStudentsToTxt() ' 替换为你的SQL Server连接字符串 Dim connStr As String = "Server=你的服务器名;Database=你的数据库名;Integrated Security=True;" Dim studentDt As New DataTable() ' 从SQL Server读取学生数据 Using sqlConn As New SqlConnection(connStr) Dim query As String = "SELECT Class, Section, StudentName, RollNo FROM students" Using sqlCmd As New SqlCommand(query, sqlConn) sqlConn.Open() Using adapter As New SqlDataAdapter(sqlCmd) adapter.Fill(studentDt) End Using End Using End Using ' 按Class和Section组合键分组 Dim groupedStudents = studentDt.AsEnumerable().GroupBy(Function(row) New With { Key .Class = row.Field(Of String)("Class"), Key .Section = row.Field(Of String)("Section") }) ' 写入Local.txt文件 Using sw As New StreamWriter("Local.txt", False, Text.Encoding.UTF8) For Each classSectionGroup In groupedStudents ' 写入分组标识 sw.WriteLine($"--- 班级: {classSectionGroup.Key.Class} 组别: {classSectionGroup.Key.Section} ---") ' 仅遍历当前分组下的学生记录 For Each studentRow In classSectionGroup sw.WriteLine($"学生姓名: {studentRow.Field(Of String)("StudentName")} 学号: {studentRow.Field(Of Integer)("RollNo")}") Next ' 分组间添加空行分隔 sw.WriteLine() Next End Using End Sub
关键修正说明
- 正确遍历分组数据:遍历分组时,使用
classSectionGroup(当前分组的元素集合)而非原studentDt.Rows,确保每个分组只输出本组的学生 - 强类型列访问:用
Field(Of T)方法读取DataRow列值,避免隐式类型转换的潜在问题 - 格式化输出:添加分组标题和空行,让输出结构更清晰易读
期望输出格式示例
--- 班级: 10 组别: A --- 学生姓名: 张三 学号: 101 学生姓名: 李四 学号: 102 --- 班级: 10 组别: B --- 学生姓名: 王五 学号: 103 学生姓名: 赵六 学号: 104 --- 班级: 9 组别: A --- 学生姓名: 孙七 学号: 901
内容的提问来源于stack exchange,提问作者Amit Kumar Yadava
相关产品推荐
相关产品推荐

