c# - Linq 将字符串转换为 Dictionary<string,string>

标签 c# linq dictionary

我正在使用字典来保存一些参数,我刚刚发现无法序列化任何实现 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/

相关文章:

c# - 将一个 List<CustomType> 复杂合并到另一个 List<CustomType>

c# - 使用 Left Join 转换 LINQ 内部联接

python - 在遍历字典列表时避免 KeyError

python - 将字符串转换为dicts python列表的列表

c# - 如何从 IOwinContext 获取 HttpRequestBase

c# - Windows 消息

c# - 如何跟踪 documentdb Linq 提供程序生成的查询?

c# - 从 SqlDataReader 获取 byte[]?

c# - Cosmos DB 在实现自定义 BotState 服务后抛出 "Resource Not Found"错误

python - 如何从 JSON 递归地在 Python 中添加字典?