Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Except using two List

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; }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading