Home > front end >  Read from CSV and convert to dictionary
Read from CSV and convert to dictionary

Time:06-08

I have a CSV file having the below values. I would like to read CSV and create a dictionary in C#. Dictionary Key = Name and Value in List<Product> such as Dictionary<string, List<Product>>

Note: In CSV, the Name can be duplicated (laptop). So I have to get a distinct Name first to get the key for the dictionary and build the Product list.

For example, in below sample data dictionary will have two key

  1. laptop (with two values)
  2. mobile (with one value)

I have found the below code but not sure how to build a dictionary based on the above requirements.

var dict = File.ReadLines("textwords0.csv").Select(line => line.Split(',')).ToDictionary(line => line[0], line => line[1]);
Name     Code  Price
laptop , 9999, 100.00
Mobile , 7777, 500.00
laptop , 9999, 100.00
public class Product 
{
    string Name {get;set;}
    string code {get;set;}
    string Price {get;set;}
}

CodePudding user response:

As the dictionary key is non-duplicate, you need a .GroupBy() to group by Name first.

  1. .GroupBy() - Group by Name, and return an IEnumerable of anonymous type with { string Name, List<Product> Products }.

  2. .ToDictionary() - Convert previous IEnumerable data to key-value pair.

var dict = File.ReadLines("textwords0.csv")
    .Select(line => line.Split(','))
    .GroupBy(
        x => x[0],
        (k, x) => new
        {
            Name = k,
            Products = x.Select(y => new Product
                            {
                                Name = y[0],
                                code = y[1],
                                Price = y[2]
                            })
                        .ToList()
        })      
    .ToDictionary(x => x.Name, x => x.Products);

Sample .NET Fiddle Demo

  • Related