views:

118

answers:

6

Hi,

I have a string like this:
"user=u123;name=Test;lastname=User"

I want to get a dictionary for this string like this:

user     "u123"  
name     "Test"  
lastname "User"

this way I can easely access the data within the string.

I want to do this in C#.

EDIT:
This is what I have so far:

public static Dictionary<string, string> ValueToDictionary(string value)
{
    Dictionary<string, string> result = null;

    result = new Dictionary<string, string>();
    string[] values = value.Split(';');

    foreach (string val in values)
    {
        string[] valueParts = val.Split('=');
        result.Add(valueParts[0], valueParts[1]);
    }

    return result;
}

But to be honest I really think there is a better way to do this.

Cheers, M.

+1  A: 
var dictionary = new Dictionary<string, string>();
var linedValue = "user=u123;name=Test;lastname=User";
var kvps = linedValue.Split(new[] { ';' }); // you may use StringSplitOptions.RemoveEmptyEntries
foreach (var kvp in kvps)
{
    var kvpSplit = kvp.Split(new[] { '=' });
    var key = kvpSplit.ElementAtOrDefault(0);
    var value = kvpSplit.ElementAtOrDefault(1);
    dictionary.Add(key, value);
    // you may check with .ContainsKey if key is already persistant
    // you may check if key and value with string.IsNullOrEmpty
}
Andreas Niedermair
+2  A: 

Split the string by ";".

Iterate over every element in the resulting array and split every element by "=".

Now; dictionary.add(element[0], element[1]);

I Hope I made it clear enough.

Undeph
+1  A: 
Dictionary<string, string> d = new Dictionary<string, string>();
string s1 = "user=u123;name=Test;lastname=User";
foreach (string s2 in s1.Split(';')) 
{
    string[] split = s2.Split('=');
    d.Add(split[0], split[1]);
}
ho1
+3  A: 

You can use LINQ:

var text = "user=u123;name=Test;lastname=User";
var dictionary = (from t in text.Split( ";".ToCharArray() )
                  let pair = t.Split( "=".ToCharArray(), 2 )
                  select pair).ToDictionary( p => p[0], p => p[1] );
TcKs
A: 

If you know for sure that there are no separator chars in your input data, the following works

string input = "user=u123;name=Test;lastname=User";
string[] fragments = input.Split(";=".ToArray());
Dictionary<string,string> result =  new Dictionary<string,string>()
for(int i=0; i<fragments.Length-1;i+=2)
  result.Add(fragments[i],fragments[i+1]);

It might perform slightly better than some of the other solutions, since it only calls Split() once. Usually I would go for any of the other solutions here, especially if readability of the code is of any value to you.

LaustN
A: 

I think I would do it like this...

String s = "user=u123;name=Test;lastname=User";
Dictionary<string,string> dict = s.ToDictionary();

The implementation of ToDictonary is the same as yours except that I would implement it as an extension method. It does look more natural.

Syd