Brini
Brini

Reputation: 47

Index was outside the bounds of the array. works in 1st example but doesn't in second

I have this example: `

var dic = File.ReadAllLines("settings.txt")
              .Select(l => l.Split(new[] { '=' }))
              .ToDictionary(s => s[0].Trim().ToString(), s => s[1].Trim().ToString());
                Variables.platefromtxt = dic["Plate"];

in my txt file I have: "Plate = -02-" So, when I want to output whats in there, I do this: Variables.platefromtxt = dic["Plate"]; Which is working fine!

I have tried to do another one:

var dicChatlog = File.ReadAllLines("chatlog.txt")
            .Select(l => l.Split(new[] { '|' }))
            .ToDictionary(s => s[0].Trim().ToString(), s => s[1].Trim().ToString());

This is what's inside my chatlog.txt: "^3-02 ^7Adorable [COP]^8 | ^7Whale Waileer"

So when I want to get "^7Whale Waileer" I should do: Variables.name = dicChatlog["^3-02 ^7Adorable [COP]^8"]

When I'm trying to run the application, I get "Index was outside the bounds of the array." The first example works just fine, the second one however has that error. Could any one tell me what I could be doing wrong?

Thanks in advance

Upvotes: 0

Views: 64

Answers (1)

Ralf Bönning
Ralf Bönning

Reputation: 15405

This should do the trick:

var dicChatlog = File.ReadAllLines("chatlog.txt")
             .Where(l => l.Contains("|"))
             .Select(l => l.Split(new[] { '|' }))
             .ToDictionary(s => s[0].Trim().ToString(), s => s[1].Trim().ToString());

Upvotes: 1

Related Questions