Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split "Path Variable" string in a Dictionary in c#

I want to break the string:

value1/672/value2/32/value3/21413

In a

Dictionary<string, string>

How can I do this without the use for a for loop?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming the provided string contains the first value as a key and the second is the value in the provided string

value1/672/value2/32/value3/21413

Here’s how you can achieve the above:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string input = "value1/672/value2/32/value3/21413";
        string[] parts = input.Split('/');
        var dictionary = parts
            .Select((value, index) => new { value, index })
            .Where(x => x.index % 2 == 0) // Select only even indexed elements as keys
            .ToDictionary(x => x.value, x => parts[x.index + 1]); // Use the next element as value      
        
        foreach (var kvp in dictionary)   // Loop for printing the result only
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");   // Output the dictionary key and values
        }
    }
}

Refer to the working .netfiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading