首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-11-07 22:05:15

只需在LINQ中使用Zip(https://msdn.microsoft.com/en-us/library/dd267698(v=vs.110%29.aspx)方法:

代码语言:javascript
复制
var actualUpdatedCareRates = currentCareRates.Zip(updatedCareRates, 
                             (f, s) => f.DayRate != s.DayRate ? s : null)
                             .Where(c => c != null).ToList();
票数 1
EN

Stack Overflow用户

发布于 2017-11-07 21:55:23

我认为,你可以使用这样的东西:

代码语言:javascript
复制
updatedCareRates.ForEach(x =>
{
    if (currentCareRates.FirstOrDefault(y => y.Id == x.Id && y.DayRate != x.DayRate) != null)
        actualUpdatedCareRates.Add(x);
});

或者一行:

代码语言:javascript
复制
updatedCareRates.Where(x => currentCareRates.FirstOrDefault(y => y.Id == x.Id &&
                            y.DayRate != x.DayRate) != null).ToList()
                           .ForEach(x => actualUpdatedCareRates.Add(x));
票数 0
EN

Stack Overflow用户

发布于 2017-11-07 22:23:03

您可以使用以下命令:

代码语言:javascript
复制
return (from up in updatedCareRates
            join cur in currentCareRates
            on up.Id equals cur.Id
            where up.DayRate != cur.DayRate
            select up).ToList();

下面是我认为查询语法比方法语法更好的罕见情况之一。

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

https://stackoverflow.com/questions/47159457

复制
相关文章

相似问题

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