Search code examples
c#.netlinqlinq-to-entities

Compare a property of an object in 2 lists


I have the following (simplified) class:

public class CareRate {

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

I would like to compare two lists of CareRate only by their DayRate; one with CareRates containing the current DayRates and one with CareRates containing the DayRates to update. Other properties which might have changed like Description, should not be taken into account.

// 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;
}

The manner to filter the changed CareRate objects by Dayrate, feels a bit devious. I think I am overlooking something. What other and better options are there for acquiring the above?


Solution

  • Simply use Zip method in LINQ:

    var actualUpdatedCareRates = currentCareRates.Zip(updatedCareRates, 
                                 (f, s) => f.DayRate != s.DayRate ? s : null)
                                 .Where(c => c != null).ToList();