我有一个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 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"},
...
而不是... {“西班牙”,[“马德里”,“巴塞罗那”,“瓦伦西亚”]} ...
你可以修改最后的.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;
}
}