2

let's say I have the following dictionary :

public Dictionary<Room, List<Booking>> rooms = new Dictionary<Room, List<Booking>>();

I need to get all available bookings regardless of the room, using lambda expression.

for example I need to do the same as the following code

List<Booking> allBookings = new List<Booking>();
        foreach (List<Booking> listOfBooking in rooms.Values)
            foreach (Booking bookingItem in listOfBooking)
                allBookings.Add(bookingItem);

any Ideas ?

Nour
  • 5,252
  • 3
  • 41
  • 66

1 Answers1

4

Sounds like you want:

var allBookings = rooms.Values.SelectMany(x => x).ToList();

Alternatively, view it as flattening by the Value property of each pair in the dictionary:

var allBookings = rooms.SelectMany(x => x.Value).ToList();

Gotta love LINQ :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That ...... is ........ awesome !!!!! yes , that is what I mean, so the question should be like: how to flatten all values in dictionary ?? – Nour Mar 10 '12 at 09:19
  • 2
    @NourSabouny: Well it's really how to flatten all the values in a dictionary, where each value is itself a collection. But your question was nice and clear, particularly as you'd given the imperative code which did what you wanted. – Jon Skeet Mar 10 '12 at 09:25
  • Thanks a lot,unfortunately I can't accept your question right now !! I have to wait a while !! – Nour Mar 10 '12 at 09:30