-1

I want to remove the one set of item in resultant list, if both Name\Type pair is same in both list. I saw Union, but it's doesn't works. it's give all 4 items.

var data1 = new List<Data>
{
    new Data{Name = "N1", Type = "T1"},
    new Data{Name = "N2", Type = "T2"},
};

var data2 = new List<Data>
{
    new Data{Name = "N1", Type = "T1"},
    new Data{Name = "N3", Type = "T3"},
};

var X = data1.Union(data2).Distinct().ToList();

The result should only contains 3 items,

new Data{Name = "N1", Type = "T1"},
new Data{Name = "N2", Type = "T2"},
new Data{Name = "N3", Type = "T3"},
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

1

Here is how you should implement and use a comparer:

class Program
{
    static void Main()
    {
        List<Dog> dogs = new List<Dog>() {
            new Dog
            {
                Age = 1,
                Name = "Fuffy"
            },
            new Dog
            {
                Age = 1,
                Name = "Fuffy"
            },
            new Dog
            {
                Age = 10,
                Name = "Pizza"
            }
        };

        var result = dogs.Distinct(new DogEqualityComparer()).ToList();
    }
}

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class DogEqualityComparer : IEqualityComparer<Dog>
{
    public bool Equals([AllowNull] Dog x, [AllowNull] Dog y)
    {
        return x?.Age == y?.Age && x?.Name == y?.Name;
    }

    public int GetHashCode([DisallowNull] Dog obj)
    {
        return (obj.Name?.GetHashCode() ?? 0) + obj.Age.GetHashCode();
    }
}
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32