我如何从 CSV 文件在 C# 中构建一个字典,其中键在一列中,值在另一列中?
How could I build a dictionary in C# from a CSV file where the keys are in one column and the values in other?
我有一个 excel 文件(用逗号分隔)两列,City
和 Country
。
A 列有国家,B 列有城市。因此,每一行都有一个国家和一个位于该国家/地区的城市。
City Country
Madrid Spain
Barcelona Spain
Paris France
Valencia Spain
Rome Italy
Marseille France
Florence Italy
我想知道如何在字典中的 C# 中阅读这个 excel > 输入键是我的国家和城市的值,所以在阅读它之后我将有以下内容:
{
"Spain": ["Madrid", "Barcelona", "Valencia"],
"France": ["Paris", "Marseille"],
"Italy": ["Rome", "Florence"]
}
到目前为止我尝试的是创建这个 class:
class ReadCountryCityFile
{
Dictionary<string, List<string>> countrycitydict{ get; }
// constructor
public ReadCountryCityFile()
{
countrycitydict= new Dictionary<string, List<string>>();
}
public Dictionary<string, List<string>> ReadFile(string path)
{
using (var reader = new StreamReader(path))
{
List<string> listcountry = new List<string>();
List<string> listcity = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != "Country;City")
{
List<string> citieslist = new List<string>();
var values = line.Split(';');
citieslist .Add(values[0]);
string country= values[1];
countrycitydict[intents] = citieslist ;
}
}
return countrycitydict;
}
}
但是countrydict
并不像预期的那样。我该怎么做?
如果
我怎么解决
City Country
Madrid Spain
我有
City Country
Madrid Spain
Valencia
如果您使用 简单 CSV(不带引号),您可以尝试 Linq:
Dictionary<string, string[]> result = File
.ReadLines(@"c:\MyFile.csv")
.Where(line => !string.IsNullOrWhiteSpace(line)) // To be on the safe side
.Skip(1) // If we want to skip the header (the very 1st line)
.Select(line => line.Split(';')) //TODO: put the right separator here
.GroupBy(items => items[0].Trim(),
items => items[1])
.ToDictionary(chunk => chunk.Key,
chunk => chunk.ToArray());
编辑: 如果需要(请参阅下面的评论)Dictionary<string, string>
(不是 Dictionary<string, string[]>
)例如你想要
...
{"Spain", "Madrid\r\nBarcelona\r\nValencia"},
...
而不是
...
{"Spain", ["Madrid", "Barcelona", "Valencia"]}
...
可以将最后的.ToDictionary
修改为:
.ToDictionary(chunk => chunk.Key,
chunk => string.Join(Environment.NewLine, chunk));
当你循环你的输入时,试着检查你的字典是否已经有键插入。如果没有插入,然后在键
处添加值
Dictionary<string, List<string>> countrycitydict{ get; }
public Dictionary<string, List<string>> ReadFile(string path)
{
using (var reader = new StreamReader(path))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != "Country;City")
{
var values = line.Split(';');
// Try to get the entry for the current country
if(!countrycitydict.TryGetValue(values[0], out List<string> v))
{
// If not found build an entry for the country
List<string> cities = new List<string>()
countrycitydict.Add(values[0], cities) ;
}
// Now you can safely add the city
countrycitydict[values[0]].Add(values[1]);
}
}
return countrycitydict;
}
}
我有一个 excel 文件(用逗号分隔)两列,City
和 Country
。
A 列有国家,B 列有城市。因此,每一行都有一个国家和一个位于该国家/地区的城市。
City Country
Madrid Spain
Barcelona Spain
Paris France
Valencia Spain
Rome Italy
Marseille France
Florence Italy
我想知道如何在字典中的 C# 中阅读这个 excel > 输入键是我的国家和城市的值,所以在阅读它之后我将有以下内容:
{
"Spain": ["Madrid", "Barcelona", "Valencia"],
"France": ["Paris", "Marseille"],
"Italy": ["Rome", "Florence"]
}
到目前为止我尝试的是创建这个 class:
class ReadCountryCityFile
{
Dictionary<string, List<string>> countrycitydict{ get; }
// constructor
public ReadCountryCityFile()
{
countrycitydict= new Dictionary<string, List<string>>();
}
public Dictionary<string, List<string>> ReadFile(string path)
{
using (var reader = new StreamReader(path))
{
List<string> listcountry = new List<string>();
List<string> listcity = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != "Country;City")
{
List<string> citieslist = new List<string>();
var values = line.Split(';');
citieslist .Add(values[0]);
string country= values[1];
countrycitydict[intents] = citieslist ;
}
}
return countrycitydict;
}
}
但是countrydict
并不像预期的那样。我该怎么做?
如果
我怎么解决City Country
Madrid Spain
我有
City Country
Madrid Spain
Valencia
如果您使用 简单 CSV(不带引号),您可以尝试 Linq:
Dictionary<string, string[]> result = File
.ReadLines(@"c:\MyFile.csv")
.Where(line => !string.IsNullOrWhiteSpace(line)) // To be on the safe side
.Skip(1) // If we want to skip the header (the very 1st line)
.Select(line => line.Split(';')) //TODO: put the right separator here
.GroupBy(items => items[0].Trim(),
items => items[1])
.ToDictionary(chunk => chunk.Key,
chunk => chunk.ToArray());
编辑: 如果需要(请参阅下面的评论)Dictionary<string, string>
(不是 Dictionary<string, string[]>
)例如你想要
...
{"Spain", "Madrid\r\nBarcelona\r\nValencia"},
...
而不是 ... {"Spain", ["Madrid", "Barcelona", "Valencia"]} ...
可以将最后的.ToDictionary
修改为:
.ToDictionary(chunk => chunk.Key,
chunk => string.Join(Environment.NewLine, chunk));
当你循环你的输入时,试着检查你的字典是否已经有键插入。如果没有插入,然后在键
处添加值Dictionary<string, List<string>> countrycitydict{ get; }
public Dictionary<string, List<string>> ReadFile(string path)
{
using (var reader = new StreamReader(path))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != "Country;City")
{
var values = line.Split(';');
// Try to get the entry for the current country
if(!countrycitydict.TryGetValue(values[0], out List<string> v))
{
// If not found build an entry for the country
List<string> cities = new List<string>()
countrycitydict.Add(values[0], cities) ;
}
// Now you can safely add the city
countrycitydict[values[0]].Add(values[1]);
}
}
return countrycitydict;
}
}