C# 将字典列表转换为字符串,反之亦然

C# 将字典列表转换为字符串,反之亦然,c#,xamarin,C#,Xamarin,我有一个字典列表,如list,我必须将其转换为String,然后再转换回相同格式的list。我试着用 string ratio = string.Join("$", order); 它转换为字符串,但我无法使用从字符串值检索回字典,但它给出了一个错误,即它无法从字符串[]转换为字典 List<String> convertStringToList = new List<Dictionary<String,String>(ratios.Split('$')); L

我有一个字典列表,如list>,我必须将其转换为String,然后再转换回相同格式的list>。我试着用

string ratio = string.Join("$", order);
它转换为字符串,但我无法使用从字符串值检索回字典,但它给出了一个错误,即它无法从字符串[]转换为字典

List<String> convertStringToList = new List<Dictionary<String,String>(ratios.Split('$'));

List convertStringToList=new List这是我能想到的最简洁的方式:

更新的开始

List<Dictionary<string, string>> convertStringToList= new   List<Dictionary<string, string>>()
List<string> strList = new List<string>();
Foreach(var dic in convertStringToList)
{
  string result = string.Join(", ", dic.Select(m => m.Key + ":" + m.Value).ToArray());
  strList.add(result);
}


希望对您有所帮助。

您可以尝试使用下面的代码片段

string ratio = string.Join("$", data);

var convertStringToList  = ratio.Split(new[] {'$'}, StringSplitOptions.RemoveEmptyEntries)
           .Select(part => part.Split(','))
            .ToDictionary(split => split[0].Trim('['), split => split[1].Trim(']'));

我推荐@Zaheer的答案,但如果你不能更改代码,你可以使用代码:

var list = new List<KeyValuePair<string, string>>(string.Join("$", dict).Split('$')
     .Select(x => 
          new KeyValuePair<String, String>(
              x.Substring(1, x.IndexOf(',')),
              x.Substring(x.IndexOf(',')+1, x.Length-x.IndexOf(',')-2))));
var list=新列表(string.Join(“$”,dict).Split(“$”)
.选择(x=>
新的KeyValuePair(
x、 子串(1,x.IndexOf(',),
x、 子串(x.IndexOf(',')+1,x.Length-x.IndexOf(',')-2));

string.Join(“$”,order)
的格式将是
[key,value]$[key,value]….

请尝试下面给出的解决方案。谢谢。我相信依赖像$这样的神奇字符串或任何类似的东西都不会有帮助。为什么不使用一个简单的xml序列化程序,它将返回一个普通的xml字符串,您可以稍后将其反序列化到对象。您能告诉我如何序列化列表吗。我已经序列化了列表,但是方法在使用字典时崩溃了。好的,谢谢,上面的方法给了我列表,但是我仍然无法获得dictionaries@apurv它应该返回类型字典。bcoz在上一条语句中,我们使用“ToDictionary”将其强制转换为dictionary。第一行给出了错误:无法从“string[]”转换为“System.Collections.Generic.IEnumerable”。是否查看了给定的引用?和更新的解决方案再次感谢,但您正在将字典转换为字符串,而我有一个字典列表。@apurv现在在更新的开始和更新的结束之间检查我的更新代码。
var list = new List<KeyValuePair<string, string>>(string.Join("$", dict).Split('$')
     .Select(x => 
          new KeyValuePair<String, String>(
              x.Substring(1, x.IndexOf(',')),
              x.Substring(x.IndexOf(',')+1, x.Length-x.IndexOf(',')-2))));