Tea*_*ild 5 c# linq dictionary
我正在使用字典来保存一些参数,我发现不可能序列化任何实现IDictionary的东西(无法序列化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);
}
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*ana 10
尝试这样的事情
var dict = str.Split(';')
.Select(s => s.Split(':'))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim()));
Run Code Online (Sandbox Code Playgroud)
对于以下类型的字符串,上面的一个是正确的
"mykey1:myvalue1; mykey2:value2;...."
Run Code Online (Sandbox Code Playgroud)
在您的代码上下文中
/// 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 = m_FtpsExtendedProperties.Split('|')
.Select(s => s.Split(','))
.ToDictionary(key => key[0].Trim(), value => value[1].Trim());
return dict;
}
set
{
// NOTE: for large dictionaries, this can use
// a StringBuilder instead of a string for cumulativeText
// does not preserve Dictionary order (if that is important - reorder the String.Format)
string newProperties =
value.Aggregate ("",
(cumulativeText,kvp) => String.Format("{0},{1}|{2}", kvp.Key, kvp.Value, cumulativeText));
// Remove the last pipe serperator
newProperties = newProperties.Substring(0, newProperties.Length - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
尚未对此进行测试,但所使用的函数应该让您了解如何使用 LINQ 相当简洁地完成此操作
| 归档时间: |
|
| 查看次数: |
15486 次 |
| 最近记录: |