CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

C# parse string split

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

Upvotes: 1

Views: 1805

Answers (3)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

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

Upvotes: 4

jflood.net
jflood.net

Reputation: 2456

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.

Upvotes: 0

Heinzi
Heinzi

Reputation: 172220

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

Upvotes: 0

Related Questions