转换 Dictionary的最佳方式转换为单个聚合字符串表示形式?
如何将键值对字典转换为单个字符串?您可以使用 LINQ 聚合来做到这一点吗?我见过使用字符串列表而不是字典来执行此操作的示例。
输入:
Dictionary<string, string> map = new Dictionary<string, string> {
{"A", "Alpha"},
{"B", "Beta"},
{"G", "Gamma"}
};
输出:
string result = "A:Alpha, B:Beta, G:Gamma";
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";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我能想到的最简洁的方法:
如果您使用 .NET 4+,您可以删除
.ToArray()
:如果您能够使用新的字符串插值语言功能:
但是,根据您的情况,这可能会更快(尽管不是很优雅):
我以不同数量的迭代运行了上述每一项(10,000;1,000,000;10,000,000)在你的三项词典和我的笔记本电脑上,后者平均快 39%。在包含 10 个元素的字典上,后者仅快 22% 左右。
另一件需要注意的事情是,我的第一个示例中的简单字符串连接比 mccow002 的答案,因为我怀疑它会用一个小字符串生成器来代替连接,因为性能指标几乎相同。
要从结果字符串重新创建原始字典,您可以执行以下操作:
This is the most concise way I can think of:
If you are using .NET 4+ you can drop the
.ToArray()
:And if you are able to use the newish string interpolation language feature:
However, depending on your circumstances, this might be faster (although not very elegant):
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:
这使用 LINQ 聚合方法:
相同,但使用
string.Format()
:This uses LINQ Aggregate method:
Same but with
string.Format()
: