2010-07-20 54 views
10

今天挣扎了一下。如果语句在Linq的where子句中

我有以下方法,返回一个产品列表......很好。

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(); 
  • 凡主要材料&源是下拉列表。

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

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

这是否有意义?!

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

+1

您能否澄清“如果未触摸基础材料ddl但选择了源ddl中的项目”? – bits 2010-07-20 14:55:40

+0

DDL的含义是什么? – 2010-07-20 14:56:08

+0

抱歉位 - 所以如果用户没有从basematerial下拉列表中选择任何内容,那么本质上数据集将不会被这个标准“过滤”。 – 2010-07-20 14:57:49

回答

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(); 
+0

你好Moi--非常感谢你的这个解决方案,它帮助我实现了很多并且很容易实现。 – 2010-07-21 11:17:55

10

考虑实施一个名为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(); 

这里,他们是两个IEnumerableIQueryable。这允许您在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; 
} 
+0

嘿那里p..campbell - 感谢您的意见,它给了我足够的思考。但是,我实现了moi的解决方案,因此标记为答案。 但是,我相信我会在某个时候使用您的解决方案,所以我会尽可能多地回答问题的答案。 – 2010-07-21 11:17:10

+2

对于IQueryable,我必须添加.AsQueryable()来返回: 'return source.Where(predicate).AsQueryable();' – 2012-12-05 18:01:51