简体   繁体   English

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

[英]converting list of dictionaries to string and vice-versa

I have a list of dictionaries as List< Dictionary< String,int>> which I have to convert to string and then convert back to the same format List< Dictionary< String,int>>. 我有一个字典列表,如List <Dictionary <String,int >>,我必须将其转换为字符串,然后再转换回相同的格式List <Dictionary <String,int >>。 I tried using 我尝试使用

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

It converts to string but I am unable to retrieve the dictionary back from string value using but it gives an error that it cannot convert from string[] to dictionary. 它可以转换为字符串,但是我无法使用从字符串值中检索出字典,但是却给出了无法将string []转换为字典的错误。

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

This is the most concise way I can think of: 这是我能想到的最简洁的方法:

Updated Start 更新开始

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);
}

Updated End 更新结束

However, depending on your circumstances, this might be faster (although not very elegant): 但是,根据您的情况,这可能会更快(尽管不是很优雅):

Foreach(var dic in convertStringToList)
    {
      string result = dic.Aggregate(new StringBuilder(),
        (a, b) => a.Append(", ").Append(b.Key).Append(":").Append(b.Value),
        (a) => a.Remove(0, 2).ToString());
      strList.add(result);
    }

Reference: 参考:

Hope it Helps. 希望能帮助到你。

You can try with below snippet. 您可以尝试以下代码段。

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(']'));

I would recommend @Zaheer 's answer, but if you can't change the code, you can use the code: 我会推荐@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))));

The format of string.Join('$', order) will be [key, value]$[key, value]..... string.Join('$', order)的格式为[key, value]$[key, value].....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM