LINQ在收集条款

问题描述:

的地方我一直在寻找谷歌,但没有找到任何对我有用的技巧。LINQ在收集条款

如你所知SQL有一个“where x in(1,2,3)”子句,它允许你检查多个值。 我正在使用linq,但我似乎无法找到与上述语句相同的语法。

我有类别的ID(列表)的集合,一个我想检查

我发现一些使用。载方法,但它甚至不建。

您必须使用包含方法您的ID列表:

var query = from t in db.Table 
      where idList.Contains(t.Id) 
      select t; 
+0

虽然我有一个跟进。 id的列是可以为空的(我通过使用value属性来忘记和修复) 如果值为null,会发生什么情况? – 2009-06-10 06:22:25

下面是说明该方法的article。您的确应该对您的收藏使用Contains方法,该方法将被翻译为IN条款。

+5

链接的文章没有更长的存在。 – MattD 2016-05-20 16:06:44

的语法如下:

IEnumerable<int> categoryIds = yourListOfIds; 

var categories = _dataContext.Categories.Where(c => categoryIds.Contains(c.CategoryId)); 

要注意的关键问题是,你做的包含您的名单上ids - 如果您正在编写sql,则不在要应用in的对象上。

这是我实现的,其中()方法,由一组选定的实体筛选IQueryable的集合:

public static IQueryable<T> WhereIn<T,TProp>(this IQueryable<T> source, Expression<Func<T,TProp>> memberExpr, IEnumerable<TProp> values) where T : class 
    { 
     Expression predicate = null; 
     ParameterExpression param = Expression.Parameter(typeof(T), "t"); 

     bool IsFirst = true; 

     MemberExpression me = (MemberExpression) memberExpr.Body; 
     foreach (TProp val in values) 
     { 
      ConstantExpression ce = Expression.Constant(val); 


      Expression comparison = Expression.Equal(me, ce); 

      if (IsFirst) 
      { 
       predicate = comparison; 
       IsFirst = false; 
      } 
      else 
      { 
       predicate = Expression.Or(predicate, comparison); 
      } 
     } 

     return predicate != null 
      ? source.Where(Expression.Lambda<Func<T, bool>>(predicate, param)).AsQueryable<T>() 
      : source; 
    } 

而且这种方法的调用看起来像:

IQueryable<Product> q = context.Products.ToList(); 

var SelectedProducts = new List<Product> 
{ 
    new Product{Id=23}, 
    new Product{Id=56} 
}; 
... 
// Collecting set of product id's  
var selectedProductsIds = SelectedProducts.Select(p => p.Id).ToList(); 

// Filtering products 
q = q.WhereIn(c => c.Product.Id, selectedProductsIds);