Robert
Robert

Reputation: 4406

How to compare two lists of objects in C#?

Lets say I have a list of objects:

public class MyObject
{
    public int ID {get;set;}
    public string Name {get;set;}
    public DateTime StartDate {get;set;}
}

now the data:

{0, "my", DateTime.Now}
{0, "List", DateTime.Now}
{0, "Data", DateTime.Now}

Now say I stripped this data from an XML or Excel document and I want to compare with what is in the database and Ignore data that already exists. I am using Entity Framework to handle this.

 public IEnumerable<MyObject> GetBy()
{
    return _context.MyObjects.OrderBy(x => x.Name);
}

I know if you want to get data from a list where it is different you use:

var myNewStuff = myStuff.Except(myDataBaseStuff);

But none of the ID properties will match so that won't work

How do I compare the two lists BASED on the Name AND StartDate values?

Upvotes: 1

Views: 96

Answers (1)

vcsjones
vcsjones

Reputation: 141688

You need to implement your own IEqualityComparer and use the overload of Except that takes it. Using Resharper, I generated this one:

public sealed class NameStartDateEqualityComparer : IEqualityComparer<MyObject>
{
    public bool Equals(MyObject x, MyObject y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        if (x.GetType() != y.GetType()) return false;
        return string.Equals(x.Name, y.Name) && x.StartDate.Equals(y.StartDate);
    }

    public int GetHashCode(MyObject obj)
    {
        unchecked
        {
            return ((obj.Name != null ? obj.Name.GetHashCode() : 0)*397) ^ obj.StartDate.GetHashCode();
        }
    }
}

Notice that the comparer only examines the Name and StartDate properties. You can of course change the comparer to your liking, like truncating the milliseconds off of the StartDate before comparing them. Then use it as such:

var myNewStuff = myStuff.Except(myDataBaseStuff, new NameStartDateEqualityComparer());

Upvotes: 4

Related Questions