我正在尝试将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
Rooms
.ForEach(room => room.RoomContents.ForEach(roomContents =>
{
Console.WriteLine("The commands for {0}",roomContents.Name);
roomContents.SupportedCommands.ForEach(command =>
Console.Writeline("{0}",command))
}));
Console.ReadLine();
尽管如此,这并不是LINQ的一个很好的用途。我自己就用线圈。
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);
}
}
}
第三种可能性是使用Aggregate来构建结果,但同样,这不是LINQ的一个很好的用途。
这将比传统的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扩展方法(