2012-09-19 47 views
0

以下是樣本字符串中的2條記錄,「|」表示新記錄或行 a「,」將這些對分開,並且「=」將該鍵與值分開。下面的代碼可以工作,如果它是單行或記錄但不是多行或在這種情況下2行。 有什麼需要做這項工作,讓我得到2行,每個3個元素?NVP ToDictionary

string s1 = "colorIndex=3,font.family=Helvicta,font.bold=1|colorIndex=7,font.family=Arial,font.bold=0"; 
string[] t = s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries); 

Dictionary<string, string> dictionary = 
       t.ToDictionary(s => s.Split('=')[0], s => s.Split('=')[1]); 
+2

你爲什麼要拆分的(和)? – aquinas

回答

2

試試這個:

var result = input.Split('|') 
        .Select(r => r.Split(',') 
           .Select(c => c.Split('=')) 
           .ToDictionary(x => x[0], x => x[1])); 
+0

您的解決方案非常出色。漂亮,簡潔。我會建議明確提到返回類型是'IEnumerable >'本來就是錦上添花。 – Enigmativity

+0

非常感謝你!這工作完美。我嘗試了其他10種方法。 – GoBeavs

0

好像你要開始與

class Font { 
    public int ColorIndex { get; set; } 
    public string FontFamily { get; set; } 
    public bool Bold { get; set; } 
} 

然後:

var fonts = s1.Split('|') 
    .Select(s => { 
     var fields = s.Split(','); 
     return new Font { 
      ColorIndex = Int32.Parse(fields[0].Split('=')[0]), 
      FontFamily = fields[1].Split('=')[1], 
      Bold = (bool)Int32.Parse(fields[2].Split('=')[2]) 
     }; 
    });