新建静态类LinqExtension,增加WhereIf。
public static class LinqExtension
{
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate).AsQueryable();
else
return source;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
if (condition)
return source.Where(predicate).AsQueryable();
else
return source;
}
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
}
调用:
当Id不为空时,进行Id查询
var catas = _imro.contextTable.Where(x => x.oid == oid&&x.stats!=990)
.WhereIf(!string.IsNullOrWhiteSpace(id), x => x.id == int.Parse(id)).ToList();