根据另一个集合值更新一个集合

时间:2015-10-06 12:49:44

标签: c# linq

您好我正在寻找基于另一个集合更新一个集合的最佳方法。

系统的第一个系统将用户视为完全可用,然后从系统获取可用性以更新集合。第一个集合需要使用第二个集合中的值进行更新。这有效,但速度很慢。

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()
};

我重构:

  • 需要在月份和年份上查找
  • 在多个数据添加月和where子句
时仍然很慢
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()
    });
}

1 个答案:

答案 0 :(得分:2)

我会使用Lookup<Tkey, TValue>快速查找每个月的百分比:

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();
}