在ForEach语句中使用linq

时间:2015-05-14 17:11:54

标签: c# linq

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

我的代码如下所示:

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

2 个答案:

答案 0 :(得分:6)

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

尽管如此,这并非使用LINQ。我自己只使用循环。

$(".website-desc").html('');

第三种可能性是使用Aggregates来构建结果,但同样,它不是很好地使用LINQ。

答案 1 :(得分:2)

传统的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扩展方法)