相关疑难解决方法(0)

为什么在重写Equals方法时重写GetHashCode很重要?

鉴于以下课程

public class Foo
{
    public int FooId { get; set; }
    public string FooName { get; set; }

    public override bool Equals(object obj)
    {
        Foo fooItem = obj as Foo;

        if (fooItem == null) 
        {
           return false;
        }

        return fooItem.FooId == this.FooId;
    }

    public override int GetHashCode()
    {
        // Which is preferred?

        return base.GetHashCode();

        //return this.FooId.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经覆盖了该Equals方法,因为它Foo代表了Foos表的一行.哪个是覆盖的首选方法GetHashCode

覆盖为什么重要GetHashCode

c# overriding hashcode

1371
推荐指数
13
解决办法
35万
查看次数

比较两个集合的相等性,而不管它们中的项目顺序如何

我想比较两个集合(在C#中),但我不确定有效实现它的最佳方法.

我已经阅读了关于Enumerable.SequenceEqual的其他帖子,但这并不是我正在寻找的.

在我的情况下,如果它们都包含相同的项目(无论顺序),则两个集合将是相等的.

例:

collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1 == collection2; // true
Run Code Online (Sandbox Code Playgroud)

我通常做的是遍历一个集合中的每个项目,看看它是否存在于另一个集合中,然后循环遍历另一个集合的每个项目,看它是否存在于第一个集合中.(我首先比较长度).

if (collection1.Count != collection2.Count)
    return false; // the collections are not equal

foreach (Item item in collection1)
{
    if (!collection2.Contains(item))
        return false; // the collections are not equal
}

foreach (Item item in collection2)
{
    if (!collection1.Contains(item))
        return false; // the collections are not equal
}

return true; // the collections are equal
Run Code Online (Sandbox Code Playgroud)

但是,这并不完全正确,并且它可能不是比较两个集合的最有效方法.

我能想到的一个例子是错误的:

collection1 …
Run Code Online (Sandbox Code Playgroud)

.net collections comparison equality

154
推荐指数
9
解决办法
9万
查看次数

在linq中设置相等

我有两个列表A和B(列表).如何以最便宜的方式确定它们是否相等?我可以写一些类似'(A减B)联合(B减A)=空集'或将它们连接在一起并计算元素数量,但它相当昂贵.有解决方法吗?

c# linq equality set

8
推荐指数
2
解决办法
4618
查看次数

标签 统计

c# ×2

equality ×2

.net ×1

collections ×1

comparison ×1

hashcode ×1

linq ×1

overriding ×1

set ×1