Как я могу построить словарь в C # из файла CSV, где ключи находятся в одном столбце, а значения в другом? - PullRequest
0 голосов
/ 31 января 2019

У меня есть файл Excel (разделенный запятыми), два столбца, City и Country.Столбец A содержит страны, а столбец B - города.Поэтому в каждом ряду есть страна и город, расположенный в этой стране.

City  Country 

Madrid    Spain    

Barcelona Spain    

Paris     France   

Valencia  Spain    

Rome      Italy    

Marseille  France   

Florence   Italy    

Мне интересно, как прочитать этот Excel в C # в типе Dictionary>, где ключом будет моя страна и значения города, поэтому после прочтения у меня будет следующее:

{
 "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   

Ответы [ 2 ]

0 голосов
/ 31 января 2019

Пока вы перебираете ввод, попробуйте проверить, есть ли в вашем словаре ключ.Если не вставить его, а затем добавить значение на ключ

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;
   }
}
0 голосов
/ 31 января 2019

Если вы используете простой 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));
...