我有以下(简化的)类:
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-08 19:58:17
我没有使用Where(x => x...),而是像发布的here一样使用Except方法来寻找解决方案。
我创建了一个类DayRateComparer,如下所示。
public class DayRateComparer : IEqualityComparer<CareRate>
{
public bool Equals(CareRate x, CareRate y) {
if (x = null) throw new ArgumentNullException(nameof(x));
if (y = null) throw new ArgumentNullException(nameof(y));
return x.Id == y.Id && x.DayRate == y.DayRate;
}
public int GetHashCode(CareRate obj) {
retun obj.Id.GetHashCode() + obj.DayRate.GetHashCode();
}
}我像这样使用DayRateComparer:
// 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
};
return updatedCareRates.Except(currentCareRates, new DayRateComparer()).ToList();
}我不喜欢使用临时列表(如actualUpdatedCareRates),在使用比较器时也不再需要使用临时列表。@S.Akbari提到的Zip方法也是一种简洁快捷的方法,但乍一看我觉得有点复杂。感谢你的帖子。
https://stackoverflow.com/questions/47159457
复制相似问题