首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >比较两个列表中对象的属性

比较两个列表中对象的属性
EN

Stack Overflow用户
提问于 2017-11-07 21:41:49
回答 4查看 103关注 0票数 0

我有以下(简化的)类:

代码语言:javascript
复制
public class CareRate {

  [Key]
  public int Id { get; set; }
  public string Description { get; set; }
  public decimal DayRate { get; set; }
}

我只想通过它们的DayRate来比较两个CareRate列表;一个包含当前DayRatesCareRates,另一个包含要更新的DayRatesCareRates。其他可能已更改的属性,如描述,不应考虑在内。

代码语言:javascript
复制
// 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对象的方式,感觉有点不靠谱。我想我忽略了一些东西。有哪些其他更好的选择可以获得上述优势?

EN

Stack Overflow用户

发布于 2017-11-08 19:58:17

我没有使用Where(x => x...),而是像发布的here一样使用Except方法来寻找解决方案。

我创建了一个类DayRateComparer,如下所示。

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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方法也是一种简洁快捷的方法,但乍一看我觉得有点复杂。感谢你的帖子。

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47159457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档