You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何读取CSV生成键为Name值为List<Product>的字典

C# 读取CSV生成Name分组的Product字典实现

需求说明

需要读取CSV文件,生成Dictionary<string, List<Product>>类型结果:

  • 字典键为CSV中去重后的Name字段值
  • 字典值为对应Name下所有Product数据组成的列表
    示例CSV中laptop出现2次、mobile出现1次,最终字典共2个键。

现有素材

参考代码(存在问题)

var dict = File.ReadLines("textwords0.csv").Select(line => line.Split(',')).ToDictionary(line => line[0], line => line[1]);

问题点:直接调用ToDictionary遇到重复Name会直接抛出键重复异常,没有映射Product实体,也没有跳过表头、处理字段前后多余空格。

示例CSV数据

Name     Code  Price
laptop , 9999, 100.00
Mobile , 7777, 500.00
laptop , 9999, 100.00

原始Product类(需修正)

public class Product 
{
    string Name {get;set;}
    string code {get;set;}
    string Price {get;set;}
}

问题点:属性没有加public修饰符,外部无法赋值访问,建议统一属性命名规范。

完整实现

第一步:修正Product类

public class Product 
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string Price { get; set; }
}

第二步:CSV读取与字典生成代码

using System.IO;
using System.Linq;
using System.Collections.Generic;

// 读取CSV解析为Product列表
var products = File.ReadLines("textwords0.csv")
    .Skip(1) // 跳过第一行表头
    .Where(line => !string.IsNullOrWhiteSpace(line)) // 过滤空行
    .Select(line =>
    {
        var columns = line.Split(',').Select(col => col.Trim()).ToArray(); // 按逗号分割,去除字段前后多余空格
        return new Product
        {
            Name = columns[0],
            Code = columns[1],
            Price = columns[2]
        };
    })
    .ToList();

// 按Name分组生成目标字典
// 如果需要不区分大小写匹配Name(比如把Mobile和mobile视为同一个键),分组时写p => p.Name.ToLowerInvariant()即可
var productDict = products
    .GroupBy(p => p.Name)
    .ToDictionary(group => group.Key, group => group.ToList());

运行结果

针对示例数据,代码运行后得到的字典包含2个键:

  • laptop:对应长度为2的List<Product>,包含2条laptop相关数据
  • Mobile:对应长度为1的List<Product>,包含1条mobile相关数据

注:如果CSV存在带引号包裹、内部含逗号的复杂字段,简单Split逻辑会解析失败,这类场景建议使用专门的CSV解析库处理。

内容的提问来源于stack exchange,提问作者itmannz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 22:36:37