2013-06-04 19 views
1

有一種情況是,我正在發送HTTP請求並從服務器獲取此響應字符串。從字符串中提取鍵值使用Linq

submitstatus: 0 
smsid: 255242179159525376 

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

我想通過使用LINQ提取關鍵值。 LINQ新增任何建議。

+0

你可以張貼streamResponse價值? – Rockstart

+0

@Rockstart流響應值提交狀態:0 smsid:255242179159525376 – ankur

回答

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

我也在以類似的方式思考。字典 outputDictionary = streamResponse.Split(':')[1] .Select(x => x).ToDictionary(y => y [0],y => y [1]);但無法弄清楚選擇聲明中應該包含哪些內容.... – ankur

0

爲什麼不使用正則表達式?水木清華這樣的:

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

爲submitstatus 和

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

的SMSID

+0

我正在尋找一個LINQ解決方案........... – ankur