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
- laptop (with two values)
- 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.
.GroupBy()
- Group byName
, and return anIEnumerable
of anonymous type with{ string Name, List<Product> Products }
..ToDictionary()
- Convert previousIEnumerable
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);