帮助对 except 扩展方法进行新的覆盖
我想编写一个新的重写 Except<
IEnumerable
的 /code>扩展方法能够内联比较器,而不是使用 IEqualityComparer。
A、B 是引用类型的集合。
类似这样的内容:
A: [1, A], [2, A], [3, A]
B: [3, B], [4, B], [5, B]
C = A.Except(B, (a,b) => a.Id == b.Id);
C: [1, A], [2, A]
我想知道您是否可以帮助我编写该方法的代码。
public static class IEnumerableExntesion
{
public IEnumerable<T> Except<T>(this IEnumerable<T> source,
IEnumerable<T> second,
Func<T, T, bool> predicate)
{
}
}
我在想:
return source.Where (s => !second.Any(p => p.Id == s.Id));
但实际上我无法使用传递的谓词将其转换为通用解决方案!
任何帮助!
I want to write a new override of Except
extension method for IEnumerable
which is able to take a comparer inline instead of using IEqualityComparer.
A, B are collections of a reference type..
Something like this:
A: [1, A], [2, A], [3, A]
B: [3, B], [4, B], [5, B]
C = A.Except(B, (a,b) => a.Id == b.Id);
C: [1, A], [2, A]
I wonder if you could help me with the code of the method.
public static class IEnumerableExntesion
{
public IEnumerable<T> Except<T>(this IEnumerable<T> source,
IEnumerable<T> second,
Func<T, T, bool> predicate)
{
}
}
I was thinking of:
return source.Where (s => !second.Any(p => p.Id == s.Id));
But actually I couldn't convert it to a generic solution using the passed predicate!
Any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否需要使用谓词进行比较,或者可以使用投影来比较投影值吗?如果是这样,那么您可以使用某种
ExceptBy
方法:Do you need to do the comparison using a predicate or can you use a projection instead and compare the projected values? If so then you could use some sort of
ExceptBy
method:这应该有效:
This should work:
我会使用您传递的
Func
来创建通用IEqualityComparer
并将其传递给常规Except
:您的扩展方法:
请注意,我有存根
GetHashCode
实现,最好正确实现它,但您必须为其传递另一个委托。I would instead use your passed
Func<T,T,bool>
to create a genericIEqualityComparer
and pass it to regularExcept
:Your extension method:
Please note that I have stub
GetHashCode
implementation, it would be better to implement it properly but you would have to pass another delegate for it.