我有以下(简化的)类:
public class CareRate {
[Key]
public int Id { get; set; }
public string Description { get; set; }
public decimal DayRate { get; set; }
}我只想通过它们的DayRate来比较两个CareRate列表;一个包含当前DayRates的CareRates,另一个包含要更新的DayRates的CareRates。其他可能已更改的属性,如描述,不应考虑在内。
// Just a test method
public List<CareRate> FilterChangedCareRates(){
var currentCareRates = new List<CareRate>{
new CareRate { Id = 1, DayRate = 3,33, Description = "Some descr" },
new CareRate { Id = 2, DayRate = 4,44, Description = "Some other descr" }
};
var updatedCareRates = new List<CareRate>{
new CareRate { Id = 1, DayRate = 2,22 },
new CareRate {Id = 2, DayRate = 4,44 } // Unchanged
};
var actualUpdatedCareRates = new List<CareRate>();
foreach(var updatedCareRate in updatedCareRates) {
var currentCareRate = currentCareRates.Single(x => x.Id == updatedCareRate.Id);
if (updatedCareRate.DayRate != currentCareRate.DayRate) {
actualUpdatedCareRates.Add(updatedCareRate);
}
}
return actualUpdatedCareRates;
}通过Dayrate过滤更改后的CareRate对象的方式,感觉有点不靠谱。我想我忽略了一些东西。有哪些其他更好的选择可以获得上述优势?
发布于 2017-11-07 22:05:15
只需在LINQ中使用Zip(https://msdn.microsoft.com/en-us/library/dd267698(v=vs.110%29.aspx)方法:
var actualUpdatedCareRates = currentCareRates.Zip(updatedCareRates,
(f, s) => f.DayRate != s.DayRate ? s : null)
.Where(c => c != null).ToList();发布于 2017-11-07 21:55:23
我认为,你可以使用这样的东西:
updatedCareRates.ForEach(x =>
{
if (currentCareRates.FirstOrDefault(y => y.Id == x.Id && y.DayRate != x.DayRate) != null)
actualUpdatedCareRates.Add(x);
});或者一行:
updatedCareRates.Where(x => currentCareRates.FirstOrDefault(y => y.Id == x.Id &&
y.DayRate != x.DayRate) != null).ToList()
.ForEach(x => actualUpdatedCareRates.Add(x));发布于 2017-11-07 22:23:03
您可以使用以下命令:
return (from up in updatedCareRates
join cur in currentCareRates
on up.Id equals cur.Id
where up.DayRate != cur.DayRate
select up).ToList();下面是我认为查询语法比方法语法更好的罕见情况之一。
https://stackoverflow.com/questions/47159457
复制相似问题