gpt4 book ai didi

c# - 联合使用 IEqualityComparer

转载 作者:可可西里 更新时间:2023-11-01 08:05:58 25 4
gpt4 key购买 nike

我只是想从两个列表中删除重复项并将它们合并到一个列表中。我还需要能够定义什么是重复项。我通过 ColumnIndex 属性定义了一个副本,如果它们相同,则它们是重复的。这是我采用的方法:

我找到了一个很好的例子,说明如何为代码段中只需要一次 em 的随机情况编写内联比较器。

public class InlineComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> getEquals;
private readonly Func<T, int> getHashCode;

public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
{
getEquals = equals;
getHashCode = hashCode;
}

public bool Equals(T x, T y)
{
return getEquals(x, y);
}

public int GetHashCode(T obj)
{
return getHashCode(obj);
}
}

然后我只有两个列表,并尝试使用比较器对它们进行联合。

            var formatIssues = issues.Where(i => i.IsFormatError == true);
var groupIssues = issues.Where(i => i.IsGroupError == true);

var dupComparer = new InlineComparer<Issue>((i1, i2) => i1.ColumnInfo.ColumnIndex == i2.ColumnInfo.ColumnIndex,
i => i.ColumnInfo.ColumnIndex);

var filteredIssues = groupIssues.Union(formatIssues, dupComparer);

然而,结果集为空。

我哪里误入歧途了?我已经确认这两个列表的列具有相同的 ColumnIndex 属性。

最佳答案

我刚刚在测试集上运行了您的代码......并且成功了!

    public class InlineComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> getEquals;
private readonly Func<T, int> getHashCode;

public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
{
getEquals = equals;
getHashCode = hashCode;
}

public bool Equals(T x, T y)
{
return getEquals(x, y);
}

public int GetHashCode(T obj)
{
return getHashCode(obj);
}
}

class TestClass
{
public string S { get; set; }
}

[TestMethod]
public void testThis()
{
var l1 = new List<TestClass>()
{
new TestClass() {S = "one"},
new TestClass() {S = "two"},
};
var l2 = new List<TestClass>()
{
new TestClass() {S = "three"},
new TestClass() {S = "two"},
};

var dupComparer = new InlineComparer<TestClass>((i1, i2) => i1.S == i2.S, i => i.S.GetHashCode());

var unionList = l1.Union(l2, dupComparer);

Assert.AreEqual(3, unionList);
}

那么...也许回去检查您的测试数据 - 或者用其他一些测试数据运行它?

毕竟 - 联合为空 - 这表明您的两个输入列表也都是空的?

关于c# - 联合使用 IEqualityComparer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5969505/

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