C# WPF读取CSV按用户名筛选记录时全量展示问题求助
问题诊断
你的代码存在4个核心逻辑错误,导致匹配规则完全不生效:
- 你声明的
wishlists是一个空的List<string[]>,全程没有添加过任何元素,遍历它的foreach循环根本不会执行,你写的用户名匹配逻辑完全没有运行机会 - 无论当前读取的CSV行是否匹配用户名,你都直接执行了
dt.Rows.Add(WishlistArray)把所有行都加入了展示用的DataTable,自然会显示全部记录 - 你创建的
Wishlist对象赋值后没有任何后续使用,属于无用代码 - DataGrid绑定逻辑写在
while循环内部,每读一行就重复绑定一次,存在不必要的性能损耗
修复后的代码
private void ViewSightings(object sender, RoutedEventArgs e) { string username = inputUsername.Text.Trim(); // 增加Trim处理输入前后的多余空格 DataTable dt = new DataTable(); // 初始化展示列 dt.Columns.Add("User", typeof(string)); dt.Columns.Add("Type", typeof(string)); dt.Columns.Add("Category", typeof(string)); dt.Columns.Add("Colour", typeof(string)); dt.Columns.Add("Size", typeof(string)); dt.Columns.Add("Sex", typeof(string)); using (StreamReader reader = new StreamReader(filepath)) { // 如果你的CSV第一行是表头,可在此处加一行reader.ReadLine()跳过表头 while (!reader.EndOfStream) { string[] lineFields = reader.ReadLine().Split(','); // 增加字段数量校验,避免行格式错误导致索引越界报错 if (lineFields.Length >= 6 && lineFields[0] == username) { // 仅匹配成功的行才加入DataTable dt.Rows.Add(lineFields); } } } // 所有行读取完成后统一绑定DataGrid dgWishlists.ItemsSource = dt.DefaultView; EnterUsernamePopup.IsOpen = false; }
额外优化建议
- 可以给用户名匹配加忽略大小写的逻辑,比如
lineFields[0].Equals(username, StringComparison.OrdinalIgnoreCase),避免大小写差异导致匹配失败 - 如果CSV字段里包含带逗号的文本,直接用
Split(',')分割会出错,建议用专用的CSV解析库处理解析逻辑
内容的提问来源于stack exchange,提问作者ash1997
相关产品推荐
相关产品推荐

