我正在尝试使用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
答案 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);
}
您还可以在所有会议室中展平和分组整个内容集。
其他好处:
foreach
循环。ToList
以访问ForEach
方法(故意不是Linq扩展方法)