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

3 Answers 3

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]);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.