stephan
stephan

Reputation: 61

Value inside a lambda statement

In the following statement i'm loading the totalscosts of a reservation of 'rentable objects'. These are added in a 'reservationline' in my reservation. A rented object has a rentalObjectType defining the type of the object. Within this 'type' the prices are stored for a date range.

I use a method "RetrievePrices(datetime,datetime)" to get the totals. This works like a charm, but it uses the StartDate & EndDate from the reservation. In some cases it is possible to have a different start and /or return date per reservation line.

I'm banging my head on how to use the reservationLine.StartDate (and EndDate) to use within the RetrievePrices() method.

I'm doing this:

 return this.Lines.Select(reservationLine => reservationLine.RentalObject)
 .Select(rentalObject => rentalObject.RentalObjectType)
 .Sum(rentalObjectType => rentalObjectType.RetrievePrices(this.StartDate, this.ReturnDate)
 .Sum(rentalObjectPrice => rentalObjectPrice.Price));

And was hoping to do something like:

return this.Lines.Select(reservationLine => reservationLine.RentalObject)
 .Select(rentalObject => rentalObject.RentalObjectType)
 .Sum(rentalObjectType => rentalObjectType.RetrievePrices(reservationLine.StartDate, reservationLine.ReturnDate)
 .Sum(rentalObjectPrice => rentalObjectPrice.Price));

Thanks in advance!

steve

Upvotes: 0

Views: 71

Answers (2)

Moeri
Moeri

Reputation: 9294

I may be missing something obvious, but wouldn't this do the trick?

return this.Lines
    .Select(reservationLine => reservationLine.RentalObject.RentalObjectType.RetrievePrices(reservationLine.StartDate,  reservationLine.ReturnDate))
    .Sum(rentalObjectPrice => rentalObjectPrice.Price));

Upvotes: 0

Andrei
Andrei

Reputation: 56688

You can skip all the selects and just do a sum right away. Then you will be able to access reservationLine in the lambda:

return this.Lines.Sum(reservationLine =>
                    reservationLine.RentalObject
                                   .RentalObjectType
                                   .RetrievePrices(reservationLine.StartDate, reservationLine.ReturnDate)
                                   .Sum(rentalObjectPrice => rentalObjectPrice.Price));

Upvotes: 3

Related Questions