考虑实施一个名为WhereIf
这些扩展方法。
您将它传递给两个参数:一个评估为布尔值的语句和一个lambda函数。如果bool语句的计算结果为true,则会添加lambda表达式。
WhereIf on ExtensionMethod.net
您的查询可能看起来像:
return getproductinfo.tblWeights
.Where(w=> w.MemberId == memberid &&
w.LocationId == locationid)
.WhereIf(!string.IsNullOrEmpty(basematerial), w=>w.BaseMaterialName == basematerial)
.WhereIf(!string.IsNullOrEmpty(source), w=>w.WeightStatus == source)
.ToList();
这里,他们是两个IEnumerable
和IQueryable
。这允许您在LINQ To SQL,实体框架,列表,数组和其他实现这两个接口的任何其他应用程序中使用.WhereIf()
。
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;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
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);
else
return source;
}
您能否澄清“如果未触摸基础材料ddl但选择了源ddl中的项目”? – bits 2010-07-20 14:55:40
DDL的含义是什么? – 2010-07-20 14:56:08
抱歉位 - 所以如果用户没有从basematerial下拉列表中选择任何内容,那么本质上数据集将不会被这个标准“过滤”。 – 2010-07-20 14:57:49