說實話,我不知道建在幫你出任何東西。這裏有兩種方式,我會考慮這樣做,
Dictionary<string, string> keyValuePairs = new Dictionary<string,string>();
string original = "Id=1000;Name=xyzabc;DB=1.2.3.4;DBUserName=admin;DBPassword";
foreach(string keyValuePair in original.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries))
{
string key = keyValuePair;
string value = string.Empty;
if (key.Contains('='))
{
key = keyValuePair.Substring(0, keyValuePair.IndexOf('='));
value = keyValuePair.Substring(keyValuePair.IndexOf('=') + 1);
}
keyValuePairs.Add(key.Trim(), value.Trim());
}
或類似的實現,
Dictionary<string, string> keyValuePairs = new Dictionary<string,string>();
string original = "Id=1000;Name=xyzabc;DB=1.2.3.4;DBUserName=admin;DBPassword";
foreach(string keyValuePair in original.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries))
{
string[] keyValues = keyValuePair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (keyValues.Length == 1)
{
keyValuePairs.Add(keyValues[0].Trim(), string.Empty);
}
else if (keyValues.Length == 2)
{
keyValuePairs.Add(keyValues[0].Trim(), keyValues[1].Trim());
}
}
這兩種解決方案給你一個字典賦予的功能做你的要求,
someObject["Id"];
我也會考慮把上面的代碼包裝到一個這樣的屬性中,
private Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
// some combination of code above to decode the original string and add
// stuff to the dictionary
public string this[string key]
{
get
{
if (keyValuePairs.ContainsKey(key))
{
return keyValuePairs[key];
}
else
{
return string.Empty;
}
}
}
因爲如果您引用不在字典中的密鑰,則字典會引發異常。
你能提供一些更詳細的信息來確定你需要完成什麼嗎?也許有人會有更好的辦法,如果你可以將你想要做的事超越你最初的問題。 – 2011-12-16 02:57:17
@AshokPadmanabhan,我已經添加了解釋,現在是否有意義? – KBBWrite 2011-12-16 03:33:13
@AshokPadmanabhan其清晰的KBBwrite所需的東西,無需進一步的信息。我正在尋找一個AddRange方法(http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx),但沒有運氣...... – 2011-12-16 03:37:58