【发布时间】:2009-06-10 06:03:23
【问题描述】:
我一直在谷歌上寻找,但没有找到任何对我有用的东西。
如您所知,SQL 有一个“where x in (1,2,3)”子句,它允许您检查多个值。 我正在使用 linq,但似乎找不到与上述语句相同的语法。
我有一个类别 ID(列表)的集合,我想检查这些
我发现了一些使用 .contains 方法的东西,但它甚至没有构建。
【问题讨论】:
标签: c# linq-to-sql
我一直在谷歌上寻找,但没有找到任何对我有用的东西。
如您所知,SQL 有一个“where x in (1,2,3)”子句,它允许您检查多个值。 我正在使用 linq,但似乎找不到与上述语句相同的语法。
我有一个类别 ID(列表)的集合,我想检查这些
我发现了一些使用 .contains 方法的东西,但它甚至没有构建。
【问题讨论】:
标签: c# linq-to-sql
语法如下:
IEnumerable<int> categoryIds = yourListOfIds;
var categories = _dataContext.Categories.Where(c => categoryIds.Contains(c.CategoryId));
要注意的关键是您在 id 列表中执行 contains - 如果您正在编写 sql,则不是在您将应用 in 的对象上。
【讨论】:
你必须在你的 id 列表中使用 Contains 方法:
var query = from t in db.Table
where idList.Contains(t.Id)
select t;
【讨论】:
这里有一个article 说明了这种方法。您确实应该在您的集合上使用 Contains 方法,该方法将被转换为 IN 子句。
【讨论】:
这是我实现的 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);
【讨论】: