字符串,字符串>到转换字典和其中的最佳方式;进入单聚集字符串重新presentation? [英] Best way to convert Dictionary<string, string> into single aggregate String representation?

查看:153
本文介绍了字符串,字符串>到转换字典和其中的最佳方式;进入单聚集字符串重新presentation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何转换键值对的字典为一个字符串?你能做到这一点使用LINQ聚集?我已经看到了使用字符串列表这样的例子,但没有一本字典。

输入:

 词典<字符串,字符串>地图=新字典<字符串,字符串> {
          {A,阿尔法},
          {B,贝塔},
          {G,伽玛}
};
 

输出:

 字符串结果=答:阿尔法,B:测试版,G:伽玛;
 

解决方案

这是最简洁的方式我能想到的:

  VAR的结果=的string.join(,map.Select(M => m.Key +:+ m.Value).ToArray());
 

不过,根据您的情况,这可能会更快(虽然不是很优雅):

  VAR的结果= map.Aggregate(新的StringBuilder()
    (A,B)=> a.Append(,).Append(b.Key).Append(:)。追加(b.Value),
    (一)=> a.Remove(0,2)的ToString());
 

在你的三个项目字典和我的笔记本电脑,后者平均39%的速度

我跑上面的每一个不同的迭代次数(10,000,000万张; 1,000,000)。在一个有10个元素的字典,后者快只有约22%。

还有一件事要注意,简单的字符串连接在我的第一个例子是比的的String.Format()变化快约38%: //stackoverflow.com/a/8002384/74757">mccow002's回答,因为我怀疑它扔在一个小字符串生成器的地方串联,赋予​​了几乎相同的性能指标。

要重新从结果字符串原来的字典,你可以做这样的事情:

  VAR地图= result.Split('')
    。选择(P => p.Trim()斯普利特(':'))
    .ToDictionary(p值=指p [0],p值=指p [1]);
 

How would I convert a dictionary of key value pairs into a single string? Can you do this using LINQ aggregates? I've seen examples on doing this using a list of strings, but not a dictionary.

Input:

Dictionary<string, string> map = new Dictionary<string, string> { 
          {"A", "Alpha"},  
          {"B", "Beta"}, 
          {"G", "Gamma"}
};

Output:

  string result = "A:Alpha, B:Beta, G:Gamma";

解决方案

This is the most concise way I can think of:

var result = string.Join(", ", map.Select(m => m.Key + ":" + m.Value).ToArray());

However, depending on your circumstances, this might be faster (although not very elegant):

var result = map.Aggregate(new StringBuilder(),
    (a, b) => a.Append(", ").Append(b.Key).Append(":").Append(b.Value),
    (a) => a.Remove(0, 2).ToString());

I ran each of the above with a varying number of iterations (10,000; 1,000,000; 10,000,000) on your three-item dictionary and on my laptop, the latter was on average 39% faster. On a dictionary with 10 elements, the latter was only about 22% faster.

One other thing to note, simple string concatenation in my first example was about 38% faster than the string.Format() variation in mccow002's answer, as I suspect it's throwing in a little string builder in place of the concatenation, given the nearly identical performance metrics.

To recreate the original dictionary from the result string, you could do something like this:

var map = result.Split(',')
    .Select(p => p.Trim().Split(':'))
    .ToDictionary(p => p[0], p => p[1]);

这篇关于字符串,字符串&gt;到转换字典和其中的最佳方式;进入单聚集字符串重新presentation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆