How to update value of LINQ results using FOREACH loop

LINQ queries are lazy loading – that means execution of reading is delayed until it’s iterated. Once set in the LINQ Select statement, the value stored in the result are set as READ ONLY hence setting the value in a FOREACH loop will not really update its data.

For example:

1 var schedules = from roomRate in _entities.RoomRates
2 select new ScheduleViewModel
3 {
4 RoomTypeId = roomRate.RoomTypeId,
5 Rates = roomRate.Rates,
6 Selling = 0,
7 Booked = 0,
8 };
9 foreach (var schedule in schedules)
10 {
11 schedule.Booked = 1;
12 schedule.Selling = 1;
13 }
Variable ‘Schedules’ field Booked and Selling  are not updated even after the FOREACH Loop.

To update the LINQ result using FOREACH loop, I first create local ‘list’ variable and then perform the update using FOREACH Loop. The value are updated this way. The example code below exemplify my idea and i further cast it back to IQueryable :)


Hotelebuddy



1 public IQueryable<ScheduleViewModel> GetScheduleForHotelBetween(int hotelId, DateTime startDate, DateTime endDate)
2 {
3 var schedules = from roomRate in _entities.RoomRates
4 join ratesTypeEnforceDate in _entities.RatesTypeEnforceDates on roomRate.RatesTypeId equals
5 ratesTypeEnforceDate.RatesTypeId
6 where roomRate.RoomType.HotelId == hotelId &&
7 ratesTypeEnforceDate.EnforceDate <= endDate &&
8 ratesTypeEnforceDate.EnforceDate >= startDate
9 select new ScheduleViewModel
10 {
11 RatesType = ratesTypeEnforceDate.RatesType.Name,
12 Date = ratesTypeEnforceDate.EnforceDate,
13 RoomTypeId = roomRate.RoomTypeId,
14 Rates = roomRate.Rates,
15 Selling = 0,
16 Booked = 0,
17 };
18 var schedulesList = new List<ScheduleViewModel>(schedules.AsEnumerable().ToList());
19 foreach (var schedule in schedulesList)
20 {
21 schedule.Booked = BookingDetails.GetBookingCountForRoomTypeOn(schedule.RoomTypeId,
22 schedule.Date);
23 schedule.Selling = RoomForSales.GetRoomForSalesCountForRoomTypeOn(schedule.RoomTypeId,
24 schedule.Date);
25 }
26
27 return (IQueryable<ScheduleViewModel>) schedulesList.AsQueryable();
28 }

Read More