Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Except not using custom Equals function

Tags:

c#

public class eq : IEquatable<eq>
    {
        public string s1;
        public string s2;
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            eq o = obj as eq;
            if (o == null) return false;
            return Equals(o);
        }
        public bool Equals(eq o)
        {
            if (s1==o.s1 && s2==o.s2)
                return true;
            return false;
        }
        public eq (string a,string b)
        {
            s1 = a;
            s2 = b;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<eq> l1 = new List<eq>();
            List<eq> l2 = new List<eq>();
            l1.Add(new eq("1", "1"));
            l1.Add(new eq("2", "2"));
            l1.Add(new eq("3", "3"));
            l2.Add(new eq("3", "3"));
            l2.Add(new eq("1", "1"));
            var b= l1.Contains(new eq("1", "1"));
            var v = l1.Except(l2);
        }
    }

The l1.contains statement calls the custom function and returns the expected result

l1.Except does not result in a call to the custom function and returns the entire contents of l1

Is there a way to accomplish this without writing loops explicitly?

like image 432
Akash Avatar asked Dec 08 '22 09:12

Akash


2 Answers

You should override GetHashCode method for Except to work properly. E.g

public override int GetHashCode()
{
    int hash = 19;
    hash = hash * 23 + (s1 == null) ? 0 : s1.GetHashCode();
    hash = hash * 23 + (s2 == null) ? 0 : s2.GetHashCode();
    return hash;
}

Except performs set operation (internally it fills Set<T> with items from second sequence and tries to add items from first sequence to same set).

like image 156
Sergey Berezovskiy Avatar answered Dec 11 '22 09:12

Sergey Berezovskiy


var v = l1.Where(x => !l2.Contains(x));

like image 20
Sushant Srivastava Avatar answered Dec 11 '22 08:12

Sushant Srivastava