[英]Update one collection based on another collection value
嗨,我正在尋找基於另一個集合更新一個集合的最佳方式。
首先,系統將用戶匹配為完全可用,然后從系統獲取可用性以更新集合。 第一個集合需要使用第二個集合中的值進行更新。 這有效但很慢。
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()
};
我重構為:
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()
});
}
我會使用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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.