-2

I have two list that I want to get the different. So because CustomerId 1 is in both I only want to return CustomerId 2. I am using Exceptbut I a returning CustomerId 1 and 2 any help would be great

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        List<Participants> Participants1 = new List<Participants>();
        Participants vm1 = new Participants();
        vm1.CustomerId = 1;
        vm1.FirstName =  "Bill";
        vm1.LastName= "Jackson";
        
        Participants1.Add(vm1);
        
        List<Participants> Participants2 = new List<Participants>();
        Participants vm2 = new Participants();
        vm2.CustomerId = 2;
        vm2.FirstName =  "Steve";
        vm2.LastName= "Jackson";
        
        Participants vm3 = new Participants();
        vm3.CustomerId = 1;
        vm3.FirstName =  "Bill";
        vm3.LastName= "Jackson";
        
        Participants2.Add(vm2);
        Participants2.Add(vm3);
        
         var inFirstOnly = Participants2.Except(Participants1);
        
        foreach(Participants item in inFirstOnly){
            Console.WriteLine(item.CustomerId);
        }
    }
    
    
    public class Participants
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Tomsen
  • 321
  • 3
  • 12
Jefferson
  • 173
  • 2
  • 12
  • 32

1 Answers1

1

To only return CustomerId 2, you need to implement a custom equality comparer to compare objects based on the CustomerId property instead of the default comparison which compares references.

public class ParticipantsComparer : IEqualityComparer<Participants>
{
    public bool Equals(Participants x, Participants y)
    {
        return x.CustomerId == y.CustomerId;
    }

    public int GetHashCode(Participants obj)
    {
        return obj.CustomerId.GetHashCode();
    }
}

Usage:

var inFirstOnly = Participants2.Except(Participants1, new ParticipantsComparer());
    
  • I would update `Equals` with the reference comparison as well just in case :) as in docs [`BoxEqVolume` part](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.equalitycomparer-1.default?view=net-7.0#examples) – Jaroslav Jan 30 '23 at 15:51