gpt4 book ai didi

c# - 根据另一个集合值更新一个集合

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:17 25 4
gpt4 key购买 nike

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

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

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

最佳答案

我会使用 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();
}

关于c# - 根据另一个集合值更新一个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32970430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com