Reputation:
One of the functions in the API I am using is returning basically just a large block of text, seperating each key/value by a semi-colon. How would I parse text like this in C#?
result=success;income_today=;income_thismonth=;income_thisyear=;orders_pending=19;orders_today_cancelled=0;orders_today_pending=0;orders_today_fraud=0;orders_today_active=0;orders_today_total=0;orders_yesterday_cancelled=0;orders_yesterday_pending=3;orders_yesterday_fraud=2;orders_yesterday_active=0;
Upvotes: 5
Views: 1313
Reputation: 117175
And here's the one-liner (formatted over multiple lines for clarity).
Dictionary<string, string> dictionary = raw
.Split(new [] { ';', }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1]);
Upvotes: 1
Reputation: 20316
I had similar problem recently. Here is a piece of code that might be useful for you. The strategy is the same as in Jon Skeet's anwers .
It looks like the keys are unique in your block of text, hence you may use Dictionary
string[] pairs = block.Split(';');
Dictionary<string, string> values = new Dictionary<string, string>();
foreach (var element in pairs)
{
var tmp = element.Split('=');
var key = tmp[0];
var val = tmp.Length == 2 ? tmp[1] : string.Empty;
values.Add(key,val );
}
foreach (var el in values)
{
Console.WriteLine(el);
}
Upvotes: 1
Reputation: 30922
I would use String.Split(Char[]). Adapting the example you would need string [] split = words.Split(new Char [] {';'});
Upvotes: 0
Reputation: 1503799
Well, that looks like a case of:
text.Split(';')
to split the block into key-value pairspair.Split('=')
on each pair to split it into key and valueNote that string.Split
has various overloads you may want to look at for options around the number of strings to return, whether to suppress empty values etc.
Upvotes: 13