c# - Using linq within a ForEach statement -
i trying use linq foreach statement display output in groups.
my code looks this:
rooms.tolist() .foreach(room => room.roomcontents.tolist() .foreach(roomcontents => roomcontents.supportedcommands.tolist() .foreach(command => console.write("\nthe commands {0} are: {1} ", roomcontents.name, command)))); console.readline(); current output:
the command tap use command key drop command key command key use command bucket drop command bucket command bucket use my aim display output in more friendly way, i.e. grouping commands based on room content. output display this.
desired output:
the commands tap use commands key drop use commands bucket drop use
this cleaner traditional foreach loops:
foreach(var room in rooms) { foreach(var roomcontents in room.roomcontents) { console.writeline("the commands {0} are:",roomcontents.name); foreach(command in roomcontents.supportedcommands) console.writeline(command); } } or slightly simplified:
foreach(var roomcontents in rooms.selectmany(room => room.roomcontents)) { console.writeline("the commands {0} are:",roomcontents.name); foreach(command in roomcontents.supportedcommands) console.writeline(command); } you flatten , group entire collection of contents in rooms.
other benefits:
- you can debug
foreachloops more embedded lambda. - you don't need call
toliston each collection in order accessforeachmethod (it's intentionally not linq extension method)
Comments
Post a Comment