c# compare the data in two object models

前端 未结 3 1259
终归单人心
终归单人心 2021-01-12 02:15

I have a dialog, when spawned it gets populated with the data in an object model. At this point the data is copied and stored in a \"backup\" object model. When the user h

3条回答
  •  不思量自难忘°
    2021-01-12 02:25

    I'd say the best way is to implement the equality operators on all classes in your model (which is usually a good idea anyway if you're going to do comparisons).

    class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public ICollection Chapters { get; set; }
    
        public bool Equals(Book other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.Title, Title) && Equals(other.Author, Author) && Equals(other.Chapters, Chapters);
        }
    
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (Book)) return false;
            return Equals((Book) obj);
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                int result = (Title != null ? Title.GetHashCode() : 0);
                result = (result*397) ^ (Author != null ? Author.GetHashCode() : 0);
                result = (result*397) ^ (Chapters != null ? Chapters.GetHashCode() : 0);
                return result;
            }
        }
    }
    

    This snippet is auto-generated by ReSharper, but you can use this as a basis. Basically you will have to extend the non overriden Equals method with your custom comparison logic.

    For instance, you might want to use SequenceEquals from the Linq extensions to check if the chapters collection is equal in sequence.

    Comparing two books will now be as simple as saying:

    Book book1 = new Book();
    Book book2 = new Book();
    
    book1.Title = "A book!";
    book2.Title = "A book!";
    
    bool equality = book1.Equals(book2); // returns true
    
    book2.Title = "A different Title";
    equality = book1.Equals(book2); // returns false
    

    Keep in mind that there's another way of implementing equality: the System.IEquatable, which is used by various classes in the System.Collections namespace for determining equality.

    I'd say check that out as well and you're well on your way!

提交回复
热议问题