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?
>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