matt
matt

Reputation: 99

Update one collection based on another collection value

Hi I am looking at the best way of updating one collection based on another collection.

First of the system matches a user as being fully available then gets availability from the system to update the collection. The first collection needs to be updated with values from the second collection. This works but is slow.

var currentDate = DateTime.Now;

// setup as fully available
var listAvailabilityNotBooked = new List<Availability>();

for (int i = -2; i < 10; i++)
{
    listAvailabilityNotBooked.Add(new Availability
    {
        Month = currentDate.AddMonths(i).Month,
        Year = currentDate.AddMonths(i).Year,
        Percentage = 0
    });
}

// match booked up from system
var availability = _availabilityRepository.GetAll();
foreach (Availability notBooked in listAvailabilityNotBooked)
{
    // not booked becomes booked if match in system
    notBooked.Percentage =
        availability.Where(i => i.Month == notBooked.Month && i.Year == notBooked.Year)
            .Select(i => i.Percentage).FirstOrDefault();
}

var availabilityDetail = new AvailabilityDetail
{
    Availability = listAvailabilityNotBooked,
    EmailEnquiryForm = new EmailEnquiryForm()
};

I refactored to:

var currentDate = DateTime.Now;

// match booked up from system
IQueryable<Availability> availability = _availabilityRepository.GetAll();

// setup as fully available
List<Availability> availabilityBooked = new List<Availability>();

for (int i = -2; i < 10; i++)
{
    var month = currentDate.AddMonths(i).Month;
    var year = currentDate.AddMonths(i).Year;

    availabilityBooked.Add(new Availability
    {
        Month = month,
        Year = year,
        Percentage = availability.Where(a => a.Month == month && a.Year == year)
          .Select(a => a.Percentage).FirstOrDefault()
    });
}

Upvotes: 2

Views: 853

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460118

I would use a Lookup<Tkey, TValue> to find the percentage for every month quickly:

var monthPercentageLookup = _availabilityRepository.GetAll()
    .ToLookup(x => new{ x.Year, x.Month }, x => x.Percentage);
foreach (Availability notBooked in listAvailabilityNotBooked)
{
    var month = new { notBooked.Year, notBooked.Month };
    notBooked.Percentage = monthPercentageLookup[month].FirstOrDefault();
}

Upvotes: 2

Related Questions