LINQ在收集条款中的位置

时间:2009-06-10 06:03:24

标签: c# linq-to-sql

我一直在寻找谷歌,但没有找到任何可以帮助我的技巧。

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

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

我找到了一些使用.contains方法的东西,但它甚至没有构建。

4 个答案:

答案 0 :(得分:40)

您必须在ID列表中使用Contains方法:

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

答案 1 :(得分:19)

语法如下:

IEnumerable<int> categoryIds = yourListOfIds;

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

需要注意的关键是你在id列表中执行包含 - 如果你正在编写sql,则不要在你要应用的对象上。

答案 2 :(得分:3)

这是一个说明方法的article。您确实应该在集合中使用Contains方法,该方法将被翻译为IN子句。

答案 3 :(得分:1)

这是我对WhereIn()方法的实现,用一组选定的实体过滤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);
相关问题