gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:22:27 26 4
gpt4 key购买 nike

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

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

l1.Except 不会调用自定义函数并返回 l1

的全部内容

有没有一种方法可以在不显式编写循环的情况下实现这一点?

最佳答案

你应该覆盖 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;
}

Except 执行集合操作(​​在内部它用第二个序列中的项目填充 Set<T> 并尝试将第一个序列中的项目添加到同一集合)。

关于c# - List.Except 不使用自定义 Equals 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22480304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com