1

I have a file consisting of two columns that will be stored as a Dictionary where the first column will be the key, and the second column will be the value. The second column is delimited by whitespace, which may be any amount of spaces or tabs.

How do I store this in my Dictionary with the Split() function?

        recipesFile = new StreamReader(recipesRes.Stream);
        char[] splitChars = {'\t', ' '};

        while (recipesFile.Peek() > 0)
        {
            string recipesLine = "";
            recipesLine = recipesFile.ReadLine();
            string[] recipesInLine = recipesLine.Split(splitChars);

            recipes.Add(recipesInLine[0], recipesInLine[1]);
        }

Thanks

CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

3 Answers3

4
recipesLine.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);

Also your code in general can be shortened to

var myDictionary = File.ReadLines(myFileName)
    .Select(l => l.Split(new []{'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
    .ToDictionary(a => a[0], a => a[1]);
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
0

Since your entries are separated using multiple whitespace characters and Split splits on single characters, you need to remove empty entries. There's a separate String.Split overload for that purpose:

string[] recipesInLine = recipesLine.Split(splitChars, 
                                           StringSplitOptions.RemoveEmptyEntries);
Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

firstly, use the file.readlines method. then you can use linq over the lines. http://msdn.microsoft.com/en-us/library/dd383503.aspx

Jon Skeet and Marc Gravell both have good examples on using linq to read files here, Reading a file line by line in C#.

Then use ToDictionary - Yuriy's answer is a good solution.

Community
  • 1
  • 1
jflood.net
  • 2,446
  • 2
  • 21
  • 19