我怎样才能在一个CSV文件中用C#构建一个字典,其中键在一列中,值在另一列中?

问题描述 投票:0回答:2

我有一个excel文件(用逗号分隔)两列CityCountry。 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   
c# dictionary readfile
2个回答
3
投票

如果您使用简单的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));

0
投票

在循环输入时尝试检查字典是否已经存在密钥插入。如果没有插入它,然后在键上添加值

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;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.