【发布时间】:2011-09-05 10:29:40
【问题描述】:
我正在使用字典来保存一些参数,但我刚刚发现无法序列化任何实现 IDictionary (unable to serialize IDictionary) 的内容。
作为一种解决方法,我想将可能的字典转换为字符串以进行序列化,然后在需要时转换回字典。
当我试图改进我的 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);
}
}
【问题讨论】:
-
顺便说一句,您可以“Linq”生成字符串:
string.Join("|", value.Select(kvp => string.Format("{0},{1}", kvp.Key, kvp.Value)))(但在 .Net 3.5 中,您需要在Select()上添加一个.ToArray())
标签: c# linq dictionary