Linq将字符串转换为Dictionary
我正在使用字典来保存一些参数,我刚刚发现不可能序列化任何实现IDictionary的东西( 无法序列化IDictionary )。
作为一种解决方法,我想将字典转换为字符串以进行序列化,然后在需要时转换回字典。
因为我正在努力改进我的LINQ,这似乎是一个很好的地方,但我不知道如何开始。
这就是我在没有LINQ的情况下实现它的方法:
/// /// Get / Set the extended properties of the FTPS processor /// /// Can't serialize the Dictionary object so convert to a string (https://msdn.microsoft.com/en-us/library/ms950721.aspx) public Dictionary FtpsExtendedProperties { get { Dictionary dict = new Dictionary(); // 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 kvp in value) { newProperties += string.Format("{0},{1}|", kvp.Key, kvp.Value); } // Remove the last pipe serperator newProperties = newProperties.Substring(0, newProperties.Length - 1); } }
在您的代码的上下文中
/// Get / Set the extended properties of the FTPS processor /// /// Can't serialize the Dictionary object so convert to a string (https://msdn.microsoft.com/en-us/library/ms950721.aspx) public Dictionary FtpsExtendedProperties { get { Dictionary 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); } }
没有对此进行测试,但所使用的function应该让您对如何使用LINQ进行相当简洁的操作有所了解
尝试这样的事情
var dict = str.Split(';') .Select(s => s.Split(':')) .ToDictionary(a => a[0].Trim(), a => a[1].Trim()));
对于以下类型的字符串,上面的一个是正确的
"mykey1:myvalue1; mykey2:value2;...."
另一个选择是使用linq-to-xml来完成繁重工作以确保所有内容都正确解析。
从…开始:
var dict = new Dictionary() { { "A", "a" }, { "B", "b" }, { "C", "c" }, };
您可以通过以下方式将其转换为xml:
var xe = new XElement("d", from kvp in dict select new XElement("p", new XAttribute("k", kvp.Key), new XAttribute("v", kvp.Value))).ToString();
哪个成了:
要将其转回字典,请使用以下命令:
var dict2 = XDocument .Parse(xml) .Root .Elements("p") .ToDictionary( x => x.Attribute("k").Value, x => x.Attribute("v").Value);
容易,对吧?
此方法将避免需要专门转义特殊字符,如“|” 要么 ”;”。
请尝试以下代码
string vals = "a|b|c|d|e"; var dict = vals.Split('|').ToDictionary(x=>x);
dict
会给你一个包含五个条目的字典。
为了您学习LINQ,我还包括序列化
var serialized = string.Join("|",from pair in value select string.Format("{0},{1}", pair.Key, pair.Value); var deserialized = new Dictionary(tokens[0],tokens[1]));
一种选择是:
- 将Dictionary转换为NameValueCollection
-
使用以下代码将NameValueCollection转换为HttpValueCollection 。
var parserCollection = HttpUtility.ParseQueryString(string.Empty); parserCollection.Add(yourNameValueCollection);
- 然后,parserCollection.ToString()将生成一个(url编码的)字典的字符串版本。
要将字符串forms转换回NameValueCollection,请使用HttpUtility.ParseQueryString(stringFormOfYourDictionary)。 然后执行与步骤1相反的操作,将NameValueCollection转换回Dictionary。
这样做的好处是无论Dictionary的内容如何,它都可以工作。 不依赖于数据的格式(因此无论字典中的键值或值如何,它都能正常工作)。
上述就是C#学习教程:Linq将字符串转换为Dictionary分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1015596.html