转换 Dictionary的最佳方式转换为单个聚合字符串表示形式?

发布于 2024-12-14 00:04:54 字数 389 浏览 3 评论 0原文

如何将键值对字典转换为单个字符串?您可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴骨ら 2024-12-21 00:04:54

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

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

如果您使用 .NET 4+,您可以删除 .ToArray()

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

如果您能够使用新的字符串插值语言功能:

var result = string.Join(", ", map.Select(m => $"{m.Key}:{m.Value}"));

但是,根据您的情况,这可能会更快(尽管不是很优雅):

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

我以不同数量的迭代运行了上述每一项(10,000;1,000,000;10,000,000)在你的三项词典和我的笔记本电脑上,后者平均快 39%。在包含 10 个元素的字典上,后者仅快 22% 左右。

另一件需要注意的事情是,我的第一个示例中的简单字符串连接比 mccow002 的答案,因为我怀疑它会用一个小字符串生成器来代替连接,因为性能指标几乎相同。

要从结果字符串重新创建原始字典,您可以执行以下操作:

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

This is the most concise way I can think of:

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

If you are using .NET 4+ you can drop the .ToArray():

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

And if you are able to use the newish string interpolation language feature:

var result = string.Join(", ", map.Select(m => $"{m.Key}:{m.Value}"));

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]);
云淡月浅 2024-12-21 00:04:54
string result = string.Join(", ", map.Select(x => string.Format("{0}:{1}", x.Key, x.Value)).ToArray())
string result = string.Join(", ", map.Select(x => string.Format("{0}:{1}", x.Key, x.Value)).ToArray())
贪恋 2024-12-21 00:04:54

这使用 LINQ 聚合方法

map
.Select(m => $"{m.Key}:{m.Value}")
.Aggregate((m1, m2) => $"{m1}, {m2}");

相同,但使用string.Format()

map
.Select(m => string.Format("{0}:{1}", m.Key, m.Value))
.Aggregate((m1, m2) => string.Format("{0}, {1}", m1, m2))

This uses LINQ Aggregate method:

map
.Select(m => $"{m.Key}:{m.Value}")
.Aggregate((m1, m2) => $"{m1}, {m2}");

Same but with string.Format():

map
.Select(m => string.Format("{0}:{1}", m.Key, m.Value))
.Aggregate((m1, m2) => string.Format("{0}, {1}", m1, m2))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文