如果Linq where子句内的语句

Ric*_*ano 10 linq if-statement where-clause

今天苦苦挣扎.

我有以下方法返回产品列表..爱.

public static List<tblWeight> GetProductInfo(string memberid, string locationid, string basematerial, string source)
        {
             MyEntities getproductinfo = new MyEntities ();

            return (from p in getproductinfo .tblWeights
                        where    p.MemberId == memberid &&
                                 p.LocationId == locationid &&
                                 p.BaseMaterialName == basematerial &&
                                 p.WeightStatus == source
                       select p)
                       .ToList();
Run Code Online (Sandbox Code Playgroud)
  • basematerial和source是下拉列表.

如何将几个IF语句合并到where子句中?

例如,如果未触摸基础材料ddl但选择了源ddl中的项目,则结果将返回与基础材料关联但由所选源过滤的所有内容.

这甚至有意义吗?!

我甚至不确定我采取了正确的方法 - 请原谅我的无知.

moi*_*eme 16

您可以根据需要将它们添加到您的查询中:

var r =  (from p in getproductinfo .tblWeights 
                        where    p.MemberId == memberid && 
                                 p.LocationId == locationid && 
                                 p.WeightStatus == source 
                       select p) 

if (!String.IsNullOrEmpty(basematrial))
    r = r.Where(p => p.BaseMaterialName == basematerial);

return r.ToList();
Run Code Online (Sandbox Code Playgroud)


p.c*_*ell 10

考虑实现这些名为的扩展方法WhereIf.

你传递了两个参数:一个被评估为布尔值的语句和一个lambda函数.如果bool语句的计算结果为true,则添加lambda.

WhereIf在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();
Run Code Online (Sandbox Code Playgroud)

他们在这里,对于他们IEnumerableIQueryable.这允许您.WhereIf()在LINQ To SQL,实体框架,列表,数组以及实现这两个接口的任何其他内容中使用.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 对于IQueryable,我必须在返回时添加.AsQueryable():`return source.Where(predicate).AsQueryable();` (2认同)