Distinct not working with LINQ to Objects

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


        
9条回答
  •  孤城傲影
    2020-11-22 12:53

    LINQ Distinct is not that smart when it comes to custom objects.

    All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields).

    One workaround is to implement the IEquatable interface as shown here.

    If you modify your Author class like so it should work.

    public class Author : IEquatable
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public bool Equals(Author other)
        {
            if (FirstName == other.FirstName && LastName == other.LastName)
                return true;
    
            return false;
        }
    
        public override int GetHashCode()
        {
            int hashFirstName = FirstName == null ? 0 : FirstName.GetHashCode();
            int hashLastName = LastName == null ? 0 : LastName.GetHashCode();
    
            return hashFirstName ^ hashLastName;
        }
    }
    

    Try it as DotNetFiddle

提交回复
热议问题