Tormod Tormod - 1 year ago 75
C# Question

Can I access the skipped "parent" of SelectMany when using dotted syntax in Linq?

In query syntax I can write

var greendoorsWithRooms = from room in house.roooms
from door in room.doors
where door.Color = green
select new {d=door,r=room}

Is there a way I could achieve the same with dotted syntax?

var greendoorsWithRooms = house.rooms.SelectMany(room=>room.Doors)
.Select(door=>new{ <room is not in scope> }

I am teaching some non-programmers to use LINQPad against a proprietary object model so that we don't have to create GUI around every odd case. It would be beneficial if they didn't have to learn query syntax. Presently, I've supplied snippets solving this using foreach, but the question still comes up once in a while.

Answer Source

This is also possible (not syntax checked):

house.rooms.SelectMany(room => room.Doors.Where(door => door.Color==green),
   (door, room) => new { d=door,r=room })

It's this overload of SelectMany.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download