C# 用readline读取可变行文本并按规则解析实现双列表框联动方法
C# 实现指定文本文件解析与列表框联动功能
第一步:定义数据存储模型
首先定义类存储每个分组的信息,方便后续数据绑定和取值:
public class SectionItem { // 第一个列表框显示的文本,如 26+017 public string DisplayText { get; set; } // 原始桩号数值,如 26017.770 public double OriginalValue { get; set; } // 归属该分组的数值对集合 public List<Tuple<double, double>> Points { get; set; } = new List<Tuple<double, double>>(); }
第二步:文本文件解析逻辑
逐行读取文件内容,自动过滤无效行,按规则归集分组数据:
// 全局数据源,存储所有解析后的分组信息 private List<SectionItem> _allSections = new List<SectionItem>(); private void LoadTargetFile(string filePath) { _allSections.Clear(); SectionItem currentSection = null; // 逐行读取,适配大文件场景,不会一次性加载全量内容 foreach (var line in File.ReadLines(filePath)) { // 过滤不符合规则的行:长度不足、前5位不是空格、第6位不是0/1 if (line.Length < 6 || !line.StartsWith(" ") || !char.IsDigit(line[5])) continue; char lineType = line[5]; // 按空白符拆分,自动忽略连续空格 var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (lineType == '1') { // 处理分组开头行,转换显示文本格式 if (double.TryParse(parts[2], out double sectionValue)) { int intValue = (int)Math.Floor(sectionValue); string prefix = (intValue / 1000).ToString(); string suffix = (intValue % 1000).ToString("D3"); currentSection = new SectionItem { OriginalValue = sectionValue, DisplayText = $"{prefix}+{suffix}" }; _allSections.Add(currentSection); } } else if (lineType == '0' && currentSection != null) { // 处理分组内的数值行,仅提取前两个数值,忽略行末标记 if (double.TryParse(parts[1], out double xVal) && double.TryParse(parts[2], out double yVal)) { currentSection.Points.Add(Tuple.Create(xVal, yVal)); } } } // 绑定数据到第一个列表框 listBox1.DataSource = null; listBox1.DataSource = _allSections; listBox1.DisplayMember = "DisplayText"; }
第三步:列表框联动逻辑
给第一个列表框添加选中项变更事件,选中时自动加载对应分组的数值对到第二个列表框:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { listBox2.Items.Clear(); if (listBox1.SelectedItem is SectionItem selectedItem) { foreach (var point in selectedItem.Points) { listBox2.Items.Add($"{point.Item1} , {point.Item2}"); } } }
使用说明
需要加载文件时,调用LoadTargetFile方法传入目标文件的完整路径即可,逻辑会自动跳过文件头部的元数据行,无需提前处理文件内容。
内容的提问来源于stack exchange,提问作者JoE
相关产品推荐
相关产品推荐

