TechSapphire Saturday, 2024-12-21, 3:09 PM
Site menu
Login form
News
Play Games
  • Deep Freeze
  • Ice Slide
  • Gyroball
  • Fat Fish
  • Bush Royal Rampage
  • Comparing 2 list of objects in C# using IEquatable

    To compare 2 list:

    Class need to implement IEquatable interface, which provide implementation of Equals method. Below is example covered in video:

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ListCompareSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                Student s1 = new Student();
                Student s2 = new Student();
                s1.Name = "hello";
                s2.Name = "hello1";
                if (s1 == s2)
                    Console.WriteLine("true");

                List<Student> list1 = new List<Student>();
                list1.Add(s1);
                list1.Add(s2);

                Student s3 = new Student();
                Student s4 = new Student();
                s3.Name = "hello";
                s4.Name = "hello1";
                List<Student> list2 = new List<Student>();
                list2.Add(s3);
                list2.Add(s4);

                if(list2.Contains(s1))
                    Console.WriteLine("true");

                if(list2.SequenceEqual(list1))
                    Console.WriteLine("true");

                if(list2.All(x=>list1.Contains(x)))
                    Console.WriteLine("true");
            }
        }
        public class Student:IEquatable<Student>
        {
            public string Name;
            public int Age=0;

            public bool Equals(Student other)
            {
                return this.Name.Equals(other.Name) && this.Age.Equals(other.Age);
            }
            public static bool operator== (Student a, Student b)
            {
                return a.Name.Equals(b.Name) && a.Age.Equals(b.Age);
            }
            public static bool operator!= (Student a, Student b)
            {
                return !(a==b);
            }
        }
    }
    Categories
    Programming [27]
    Tips for programming
    Security [2]
    Security Tips
    Google [1]
    Use google faster then ever you use
    Project [14]
    HTML [2]
    Electronics [0]
    Data Structure [0]
    Database [16]
    SQL SERVER
    SSRS [1]
    Sql Server Reporting Services
    Copyright MyCorp © 2024