我正在尝试在我的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/