我正在使用字典来保存一些参数,我刚刚发现无法序列化任何实现 IDictionary ( unable to serialize IDictionary ) 的东西。
作为解决方法,我想将 may 字典转换为字符串以进行序列化,然后在需要时转换回字典。
因为我正在尝试改进我的 LINQ,这似乎是一个很好的地方,但我不确定如何开始。
这就是我在没有 LINQ 的情况下实现它的方式:
/// <summary>
/// Get / Set the extended properties of the FTPS processor
/// </summary>
/// <remarks>Can't serialize the Dictionary object so convert to a string (http://msdn.microsoft.com/en-us/library/ms950721.aspx)</remarks>
public Dictionary<string, string> FtpsExtendedProperties
{
get
{
Dictionary<string, string> dict = new Dictionary<string, string>();
// Get the Key value pairs from the string
string[] kvpArray = m_FtpsExtendedProperties.Split('|');
foreach (string kvp in kvpArray)
{
// Seperate the key and value to build the dictionary
string[] pair = kvp.Split(',');
dict.Add(pair[0], pair[1]);
}
return dict;
}
set
{
string newProperties = string.Empty;
// Iterate through the dictionary converting the value pairs into a string
foreach (KeyValuePair<string,string> kvp in value)
{
newProperties += string.Format("{0},{1}|", kvp.Key, kvp.Value);
}
// Remove the last pipe serperator
newProperties = newProperties.Substring(0, newProperties.Length - 1);
}
}
最佳答案
尝试这样的事情
var dict = str.Split(';')
.Select(s => s.Split(':'))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim()));
以上一条适用于下列类型的字符串
"mykey1:myvalue1; mykey2:value2;...."
关于c# - Linq 将字符串转换为 Dictionary<string,string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7306767/