Distinct not working with LINQ to Objects

后端 未结 9 1812
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 12:20
class Program
{
    static void Main(string[] args)
    {
        List books = new List 
        {
            new Book
            {
                


        
9条回答
  •  情深已故
    2020-11-22 12:45

    Distinct() performs the default equality comparison on objects in the enumerable. If you have not overridden Equals() and GetHashCode(), then it uses the default implementation on object, which compares references.

    The simple solution is to add a correct implementation of Equals() and GetHashCode() to all classes which participate in the object graph you are comparing (ie Book and Author).

    The IEqualityComparer interface is a convenience that allows you to implement Equals() and GetHashCode() in a separate class when you don't have access to the internals of the classes you need to compare, or if you are using a different method of comparison.

提交回复
热议问题