使用没有外部变量的LINQ从字典(值)中Concat所有字符串

Tat*_*ved 4 c# linq dictionary concat

拥有字典,其中键可以是任何东西(例如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.");
Run Code Online (Sandbox Code Playgroud)

获得输出:

string lResult = dict. ... //there should go the LINQ query
Console.WriteLine(lResult);
Run Code Online (Sandbox Code Playgroud)

输出:

This is the first line.
This is the second line.
This is the third line.
Run Code Online (Sandbox Code Playgroud)

问:是否有可能将这些行连接起来Dictionary,将它们作为一个字符串而不使用外部变量?


我试过使用一些Select/SelectMany/Zip解决方案,但我无法想象如何在不使用外部变量的情况下将1 LINQ调用的值传递给其他人.

另一个想法是Select值,将它们放到List然后连接(再次使用外部变量).喜欢:

string tmp = "";
dict.Select(a => a.Value).ToList().ForEach(b => tmp += b);
Run Code Online (Sandbox Code Playgroud)

Ren*_*ogt 11

您不应该使用LINQ来连接字符串.这可能变得非常昂贵.使用string.Join()innstead:

string result = string.Join(Environment.NewLine, dict.Values);
Run Code Online (Sandbox Code Playgroud)

但是,这并不能保证正确的顺序,因为a Dictionary<>没有排序.要按Keys 对输出进行排序,您可以执行以下操作:

string sorted = string.Join(Environment.NewLine, 
                     dict.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value));
Run Code Online (Sandbox Code Playgroud)