东西比较简单,大家一看就明白,不多做解释,直接上代码
public static class LinqExtend
{
public static IQueryable<TSource> WhereIn<TSource, TKey>(this IQueryable<TSource> source, IEnumerable<TKey> source2,
Expression<Func<TSource, TKey>> keySelector)
{
Expression inExpression = GetInExpression(source2, keySelector);
return source.Where(Expression.Lambda<Func<TSource, bool>>(inExpression, keySelector.Parameters));
}
public static IQueryable<TSource> WhereNotIn<TSource, TKey>(this IQueryable<TSource> source, IEnumerable<TKey> source2,
Expression<Func<TSource, TKey>> keySelector)
{
Expression inExpression = GetInExpression(source2, keySelector);
Expression notInExpression = Expression.Not(inExpression);
return source.Where(Expression.Lambda<Func<TSource, bool>>(notInExpression, keySelector.Parameters));
}
private static Expression GetInExpression<TSource, TKey>(IEnumerable<TKey> source2,
Expression<Func<TSource, TKey>> keySelector)
{
if (null == keySelector)
throw new ArgumentNullException("keySelector");
if (null == source2)
throw new ArgumentNullException("source2");
if (source2.Count() == 0)
return Expression.Constant(true);
Type genericType = typeof(List<>).MakeGenericType(typeof(TKey));
var conExp = Expression.Constant(source2.ToList(), genericType);
MethodInfo methodInfo = genericType.GetMethods().FirstOrDefault(m => m.Name.Equals("Contains")
&& m.GetParameters().Count() == 1 && m.GetParameters().FirstOrDefault().ParameterType == typeof(TKey));
var bodyExp = Expression.Call(conExp, methodInfo, keySelector.Body);
return bodyExp;
}
该博客介绍了如何通过扩展LINQ方法来实现基于`whereIn`和`whereNotIn`的查询过滤功能。提供的代码示例展示了如何创建这两个方法,它们分别用于筛选集合中包含和不包含指定值的元素。方法内部利用了`Expression`构建查询表达式,并结合`Contains`方法完成过滤操作。
234

被折叠的 条评论
为什么被折叠?



