Select entities where ID in int array - WCF Data Services, LINQ

后端 未结 3 471
不思量自难忘°
不思量自难忘° 2020-12-19 09:27

I would like to return a set of entities who has and ID that is contained in a list or array of IDs using LINQ and Data Services. I know how to this using LinqToEF but I am

3条回答
  •  旧巷少年郎
    2020-12-19 09:37

    Here is my realization of WhereIn() Method, to filter IQueryable collection by a set of selected entities:

     public static IQueryable WhereIn(this IQueryable source, Expression> memberExpr, IEnumerable values) where T : class
        {
            Expression predicate = null;
            ParameterExpression param = Expression.Parameter(typeof(T), "t");
    
            bool IsFirst = true;
    
            // Create a comparison for each value eg:                 
            // IN:  t => t.Id == 1 | t.Id == 2                
    
            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>(predicate, param)).AsQueryable()
                : source;
        }
    

    And calling of this method looks like:

    IQueryable q = context.Products.ToList();
    
    var SelectedProducts = new List
    {
      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);
    

提交回复
热议问题