List.Except不使用自定义Equals函数

Aka*_*ash 3 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

l1.contains语句调用自定义函数并返回预期结果

l1.Except 不会导致调用自定义函数并返回整个内容 l1

有没有办法在不明确编写循环的情况下完成此操作?

Ser*_*kiy 9

您应该覆盖正常工作的GetHashCode方法Except.例如

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;
}
Run Code Online (Sandbox Code Playgroud)

除了执行设置操作(在内部,它填充Set<T>第二个序列中的项目并尝试将项目从第一个序列添加到同一个集合).

  • @Akash所有哈希码的要求是如果两个对象比较相等,则它们必须*返回相同的哈希码. (2认同)