gpt4 book ai didi

c# - 我可以将 Linq 的 Except() 与 lambda 表达式比较器一起使用吗?

转载 作者:IT王子 更新时间:2023-10-29 04:10:19 27 4
gpt4 key购买 nike

我知道我可以调用 linq 的 Except 并指定一个自定义的 IEqualityComparer,但是为每个数据类型实现一个新的 Comparer 类似乎有点矫枉过正。我可以使用 lambda 表达式来提供相等函数,就像我使用 Where 或其他 LINQ 函数时一样吗?

如果我不能,是否有其他选择?

最佳答案

对于任何仍在寻找的人;这是实现自定义 lambda 比较器的另一种方法。

public class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _expression;

public LambdaComparer(Func<T, T, bool> lambda)
{
_expression = lambda;
}

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

public int GetHashCode(T obj)
{
/*
If you just return 0 for the hash the Equals comparer will kick in.
The underlying evaluation checks the hash and then short circuits the evaluation if it is false.
Otherwise, it checks the Equals. If you force the hash to be true (by assuming 0 for both objects),
you will always fall through to the Equals check which is what we are always going for.
*/
return 0;
}
}

然后你可以为 linq 创建一个扩展,除了一个接受 lambda 的相交

/// <summary>
/// Returns all items in the first collection except the ones in the second collection that match the lambda condition
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="listA">The first list</param>
/// <param name="listB">The second list</param>
/// <param name="lambda">The filter expression</param>
/// <returns>The filtered list</returns>
public static IEnumerable<T> Except<T>(this IEnumerable<T> listA, IEnumerable<T> listB, Func<T, T, bool> lambda)
{
return listA.Except(listB, new LambdaComparer<T>(lambda));
}

/// <summary>
/// Returns all items in the first collection that intersect the ones in the second collection that match the lambda condition
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="listA">The first list</param>
/// <param name="listB">The second list</param>
/// <param name="lambda">The filter expression</param>
/// <returns>The filtered list</returns>
public static IEnumerable<T> Intersect<T>(this IEnumerable<T> listA, IEnumerable<T> listB, Func<T, T, bool> lambda)
{
return listA.Intersect(listB, new LambdaComparer<T>(lambda));
}

用法:

var availableItems = allItems.Except(filterItems, (p, p1) => p.Id== p1.Id);

关于c# - 我可以将 Linq 的 Except() 与 lambda 表达式比较器一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6277760/

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