1

There is a scenario in which I am sending an HTTP request and getting this response String from the server.

submitstatus: 0
smsid: 255242179159525376

         var streamResponse = newStreamReader(response.GetResponseStream()).ReadToEnd().ToString();

I want to extract the key values by using LINQ. New to LINQ any suggestions.

4

2 回答 2

2

I am using output string to simulate the result

string output = @"submitstatus: 0
smsid: 255242179159525376";

// you can use regex to match the key/value
// what comes before `:` will be the key and after the value
var matches = Regex.Matches(output, @"(?<Key>\w+):\s(?<Value>[^\n]+)");

// for each match, select the `Key` match as a Key for the dictionary and
// `Value` match as the value
var d = matches.OfType<Match>()
    .ToDictionary(k => k.Groups["Key"].Value, v => v.Groups["Value"].Value);

So you will have a Dictionary<string, string> with keys and values.


Using Split method

var keysValues = output.Split(new string[] { ":", "\r\n" },
                     StringSplitOptions.RemoveEmptyEntries);

Dictionary<string, string> d = new Dictionary<string, string>();
for (int i = 0; i < keysValues.Length; i += 2)
{
    d.Add(keysValues[i], keysValues[i + 1]);
}

Trying to use purely Linq

var keysValues = output.Split(new string[] { ":", "\r\n" },
                     StringSplitOptions.RemoveEmptyEntries);
var keys = keysValues.Where((o, i) => (i & 1) == 0);
var values = keysValues.Where((o, i) => (i & 1) != 0);
var dictionary = keys.Zip(values, (k, v) => new { k, v })
                     .ToDictionary(o => o.k, o => o.v);
于 2013-06-04T07:16:04.567 回答
0

Why dont you use regex? Smth like:

(?<=submitstatus:\s)\d+ 

for submitstatus and

(?<=smsid:\s)\d+ 

for smsid

于 2013-06-04T07:11:12.167 回答