c# - 在ForEach语句中使用linq

标签 c# linq

我正在尝试在我的ForEach语句中使用Linq以分组显示输出。

我的代码如下所示:

Rooms.ToList()
     .ForEach(room => room.RoomContents.ToList()
         .ForEach(roomContents => roomContents.SupportedCommands.ToList()
             .ForEach(command => Console.Write("\nThe commands for {0} are: {1} ", roomContents.Name, command))));          

Console.ReadLine();


电流输出:

The command for Tap are Use
The command for Key are Drop
The command for Key are Get
The command for Key are Use
The command for Bucket are Drop
The command for Bucket are Get
The command for Bucket are Use


我的目的是以更友好的方式显示输出,即根据房间内容对命令进行分组。我希望输出显示类似这样的内容。

所需输出:

The commands for Tap 
Use
The commands for Key 
Drop
Get
Use
The commands for Bucket
Drop
Get
Use

最佳答案

与传统的foreach循环相比,这将更加干净:

foreach(var room in Rooms)
{
    foreach(var roomContents in room.RoomContents)
    {
        Console.WriteLine("The commands for {0} are:",roomContents.Name);
        foreach(command in roomContents.SupportedCommands)
            Console.WriteLine(command);
    }
}


或略作简化:

foreach(var roomContents in Rooms.SelectMany(room => room.RoomContents))
{
    Console.WriteLine("The commands for {0} are:",roomContents.Name);
    foreach(command in roomContents.SupportedCommands)
        Console.WriteLine(command);
}


您还可以将所有房间中的所有内容拼合起来并进行分组。

其他福利:


与嵌入式lambda相比,您可以轻松调试foreach循环。
您无需在每个集合上调用ToList即可访问ForEach方法(故意不是Linq扩展方法)

关于c# - 在ForEach语句中使用linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30243307/

相关文章:

c# - 如何使用 SqlParameterCollection?

c# - 将 linq to objects 查询结果放入类型字典中

c# - Linq 选择两个列表中都存在的项目

c# - 如何使用 C# 中的 linq 检查存储在具有给定值的数据库列中的逗号分隔值

c# - 如何对打印到物理打印机的功能进行单元测试?

c# - LINQ 从 3 个表中选择 Dish/Images/ImageDish

C# MVC ViewModel 返回 Null - 回传

linq - MongoDb c# Linq 查询并返回集合的子对象

c# - 如何在 visual studio 中添加程序集 DocumentFormat.OpenXml.Wordprocessin

c# - 在没有 For 表达式的情况下扩展 ASP.NET Core InputTagHelper 类时出现 NullReferenceException