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

标签 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.");

获取输出:

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/

相关文章:

asp.net-mvc - .Net MVC 在编辑器模板中获取 Lambda 表达式

python - 字典中的最高值

java - 使用java构建字典

c# - 将数据类型 nvarchar 转换为 int 时出错 - 执行存储过程时

c# - Microsoft ASP.NET Identity - 多个用户同名

c# - 从 MySqlReader 读取

linq - 自动生成的 sql 代码 : single backslash as an escape character is failing

c# - Linq 混合扩展和查询语法

java - 为什么 Map.getOrDefault() 会警告 NullPointerException?

c# - Autofac 异常 : Cannot resolve parameter of constructor 'Void . 构造函数