我正在使用一个字典来保存一些参数,但我发现无法序列化实现IDictionary接口的任何内容(无法序列化IDictionary)。
为了解决这个问题,我想将字典转换为字符串进行序列化,然后在需要时再转换回字典。
由于我正在尝试改善我的LINQ,所以这似乎是一个好地方,但我不确定该如何开始。
以下是没有使用LINQ实现的示例:
为了解决这个问题,我想将字典转换为字符串进行序列化,然后在需要时再转换回字典。
由于我正在尝试改善我的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);
}
}
string.Join("|", value.Select(kvp => string.Format("{0},{1}", kvp.Key, kvp.Value)))
(但在.NET 3.5中,你需要在Select()
上加上.ToArray()
)。 - Andras Zoltan