gpt4 book ai didi

c# - 使用没有外部变量的 LINQ 连接字典(值)中的所有字符串

转载 作者:太空狗 更新时间:2023-10-30 00:01:15 24 4
gpt4 key购买 nike

有字典,其中键可以是任何东西(例如 int),值是我想要输出的一些文本。

Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "This is the first line.");
dict.Add(2, "This is the second line.");
dict.Add(3, "This is the third line.");

获取输出:

string lResult = dict. ... //there should go the LINQ query
Console.WriteLine(lResult);

输出:

This is the first line.
This is the second line.
This is the third line.

问:是否可以在不使用外部变量的情况下将 Dictionary 中的行连接成一个字符串?


我尝试使用一些 Select/SelectMany/Zip 解决方案,但我不知道如何在不使用外部变量的情况下将值从 1 个 LINQ 调用传递给其他调用。

另一个想法是选择 值,将它们放入列表,然后连接(再次使用外部变量)。喜欢:

string tmp = "";
dict.Select(a => a.Value).ToList().ForEach(b => tmp += b);

最佳答案

您不应使用 LINQ 来连接字符串。这可以变成very expenisve .使用 string.Join() 相反:

string result = string.Join(Environment.NewLine, dict.Values);

但是,这并不能保证顺序正确,因为 Dictionary<>未排序。按 Key 对输出进行排序你可以这样做:

string sorted = string.Join(Environment.NewLine, 
dict.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value));

关于c# - 使用没有外部变量的 LINQ 连接字典(值)中的所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com