簡體   English   中英

在ForEach語句中使用linq

[英]Using linq within a ForEach statement

我正在嘗試在我的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
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);
    }
  }
}

第三種可能性是使用聚合來生成結果,但同樣,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擴展方法)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM