1

I have a string like this:

Option1: Value1
Option2: Value2
Option3: Value3

I am trying to put this into a multidimensional array so that I can then lookup the values depending on what I put for 'Option', it will return the value.

So far I have this which will put each line into the array:

string[] Header = Headers.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

I am unsure how to split this into a 2 dimensional array so that it will split the line based on the colon delimiter?

How can I then perform a lookup? for example in PHP I would use the varible: $Header['Option2'] in order to return the value for "Option2".

Thanks.

1
  • Could you add to your question an example of the output you desire. Commented Oct 9, 2018 at 14:50

1 Answer 1

6

You can construct the lookup dictionary entirely with LINQ:

var dictionary = text.Split(new []{Environment.NewLine}, StringSplitOptions.None)
          .Select(line => line.Split(':'))
          .ToDictionary(lineParts => lineParts[0], lineParts => lineParts[1]);

Explanation on what it does in simple code:

var lines = text.Split(new []{Environment.NewLine}, StringSplitOptions.None); //split the string in lines
var dictionary = new Dictionary<string, string>();
foreach (var line in lines)
{
    var lineParts = line.Split(':'); //split line to parts with : as delimiter
    var key = lineParts[0]; //first part is the key
    var value = lineParts[1]; //second part is the value
    dictionary.Add(key, value);
}

Now you can simply lookup like this:

var value = dictionary["Option2"];
Sign up to request clarification or add additional context in comments.

15 Comments

Style question: did you mean to put the . at the end of the preceding line rather than before the method name? I've not seen that done before and if I'm honest, I hate it!
Oh also, though OP doesn't specify clearly, you probably need to Trim the value.
@phuzi I think the reason OP asked for two-dimensional array is the fact that PHP would approach the problem this way, in C# Dictionary is I think the correct counterpart
And while I'm here (sorry!) I would also recommend doing line.Split(new[] { ':' }, 1)) in case the value contains a :
(because what you have here doesn't actually compile...)
|

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.