HTTP 要求を送信し、サーバーからこの応答文字列を取得するシナリオがあります。
submitstatus: 0
smsid: 255242179159525376
var streamResponse = newStreamReader(response.GetResponseStream()).ReadToEnd().ToString();
LINQ を使用してキー値を抽出したいと考えています。LINQ の新しい提案。
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);
正規表現を使用しないのはなぜですか?次のようなものです:
(?<=submitstatus:\s)\d+
submitstatus と
(?<=smsid:\s)\d+
smsid の