C# string list to Dictionary

Markus Freitag 3,786 Reputation points
2021-01-16T11:22:47.793+00:00

Hello,

I get this string back. Always with a carriage return. Do I have to create a key value from this? It's sure to be easy. Which is best?

String ret="Speed=300
Color=“Red“
Order=“35253256“
ProductID=342424
Price=“349 €“
Tax=“19%“
Electricity=2,55
Comment=“230V 2,55A“"

Goal
key = Color value = "Red"
key= Price value = 349 €

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,390 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,201 Reputation points
    2021-01-16T13:52:42.863+00:00

    Hello @Markus Freitag

    See if this works for you.
    57217-11111111111.png

    private void Demo()  
    {  
        var ret =   
            "Speed=300\nColor=\"Red\"\nOrder=\"35253256\"\n" +   
            "ProductID=342424\nPrice=\"349 €\"\nTax=\"19%\"\n" +   
            "Electricity=2,55\nComment=\"230V 2,55A\"";  
          
        var itemsList = ret.Split('\n').Select(item =>  
        {  
            var parts = item.Split('=');  
            return new {Key = parts[0], Value = parts[1]};  
        }).ToList();  
      
        var dict = new Dictionary<string, string>();  
        foreach (var line in itemsList)  
        {  
            dict.Add(line.Key, line.Value);  
        }  
         
    }  
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful