【发布时间】:2016-07-15 21:09:43
【问题描述】:
我有 List
初始列表
List<Rates> rates = new List<Rates>()
{
new Rates { CheckInDate = timeValue, websiteId = 1, price = 1 },
new Rates { CheckInDate = timeValue, websiteId = 1, price = 2 },
new Rates { CheckInDate = timeValue, websiteId = 2, price = -1 },
new Rates { CheckInDate = timeValue, websiteId = 2, price = 2 },
new Rates { CheckInDate = timeValue, websiteId = 3, price = -1 },
new Rates { CheckInDate = timeValue, websiteId = 3, price = -1 },
};
最终名单
List<Rates> rates = new List<Rates>()
{
new Rates { CheckInDate = timeValue, websiteId = 1, price = 1 },
new Rates { CheckInDate = timeValue, websiteId = 2, price = 2 },
new Rates { CheckInDate = timeValue, websiteId = 3, price = -1 },
};
我已经尝试过这段代码,但是遍历循环需要很多时间。 首先,我通过 CheckInDate、WebsiteId 找到了不同的组。 然后对于每个组,我正在检查所需的费率。
class Rates {
public int websiteId {get; set;},
public DateTime CheckInDate {get; set;}
public decimal price {get; set;}}
var grouped = (from s in finalReportDetails
select new { s.CheckInDate,s.websiteId })
.Distinct()
.ToList();
for (int i = 1; i <= grouped.Count && finalReportDetails.Count != grouped.Count; i++)
{
var obj = grouped[i - 1];
// Fetch records for one group, order by rate to find the least Rate
var grpFinalReportDetails = (from s in Rates
where && s.CheckInDate == obj.CheckInDate && s.websiteId == obj.websiteId
select s).OrderBy(x => x.price).ToList();
// Deletion necessary only if there is more than one rate for same parameters
if (grpFinalReportDetails.Count > 1)
{
// Tracks if a valid rate is found
bool isFound = false;
for (int j = 0; j < grpFinalReportDetails.Count; j++)
{
// Checks if a valid least rate is found
if (!isFound && grpFinalReportDetails[j].InitialRates.Rates > 0)
{
isFound = true;
continue;
}
// Delete all but one records whose Rate is less than 0 OR whose rate is more than the cheapest rate
if ((grpFinalReportDetails[j].InitialRates.Rates <= 0 && j < grpFinalReportDetails.Count - 1) || isFound)
{
finalReportDetails.Remove(grpFinalReportDetails[j]);
}
}
}
}
有没有更快的方法来使用 linq 找到相同的内容? 或者可以在这段代码中优化的东西。
【问题讨论】: