1

HTTP 要求を送信し、サーバーからこの応答文字列を取得するシナリオがあります。

submitstatus: 0
smsid: 255242179159525376

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

LINQ を使用してキー値を抽出したいと考えています。LINQ の新しい提案。

4

2 に答える 2

2

output結果をシミュレートするために文字列を使用しています

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);

したがってDictionary<string, string>、キーと値を持つ があります。


使用Split方法

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]);
}

純粋に使おうとする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

正規表現を使用しないのはなぜですか?次のようなものです:

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

submitstatus と

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

smsid の

于 2013-06-04T07:11:12.167 に答える