Quantcast
Channel: 技术笔记 –龙堂
Viewing all articles
Browse latest Browse all 40

Compare two lists of objects by specific properties

$
0
0

Credit goes: http://stackoverflow.com/questions/19790211/comparing-two-lists-according-to-specific-properties

.Net Except with IEqualityComparer

// define the Animal class
public class Animal
{
	public Guid Id { get; set; }
	public string AnimalName { get; set; }
	public bool HasTail { get; set; }
}

And then have the following, expect that these two list should be equal to each other, but actually not

var id = Guid.NewGuid();
var animalList1 = new List<Animal>{new Animal { Id=id, AnimalName="cat", HasTail=true}};
var animalList2 = new List<Animal>{new Animal { Id=id, AnimalName="cat", HasTail=true}};

var isSame = !animalList1.Except(animalList2).Any() // expect to be true, but it's false;

In this case, need to implement it’s own IEqualityComparer

public class AnimalComparer : IEqualityComparer<Animal>
{
    ///
<summary>
    /// Implement the Equals methods
    /// </summary>

    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    public bool Equals(Animal x, Animal y)
    {
        return x.Id.Equals(y.Id) && x.AnimalName.Equals(y.AnimalName) && x.HasTail == y.HasTail;
    }

    ///
<summary>
    /// Implement its own GetHashCode method
    /// </summary>

    /// <param name="x"></param>
    /// <returns></returns>
    public int GetHashCode(Animal x)
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + x.Id.GetHashCode();
            hash = hash * 23 + x.AnimalName.GetHashCode();
            hash = hash * 23 + x.HasTail.GetHashCode();
            return hash;
        }
    }
}

And now if compare these two lists by using its own comparer, it will succeed

var isSame = !animalList1.Except(animalList2, new AnimalComparer()).Any(); // Now will be true


Viewing all articles
Browse latest Browse all 40

Trending Articles