linq to sql 中的in 操作实现

/// <summary> /// 建立 In 查询条件 /// </summary> /// <typeparam name="T">实体</typeparam> /// <param name="q">动态查询条件创建者</param> /// <param name="property">属性</param> /// <param name="valuse">查询值</param> /// <returns></returns> public static IQueryBuilder<T> In<T,P>(this IQueryBuilder<T> q, Expression<Func<T, P>> property, params P[] values) { if (values != null && values.Length > 0) { var parameter = property.GetParameters(); var constant = Expression.Constant(values); Type type = typeof(P); Expression nonNullProperty = property.Body; //如果是Nullable<X>类型,则转化成X类型 if (IsNullableType(type)) { type = GetNonNullableType(type); nonNullProperty = Expression.Convert(property.Body, type); } Expression<Func<P[], P, bool>> InExpression = (list, el) => list.Contains(el); var methodExp = InExpression; var invoke = Expression.Invoke(methodExp, constant, property.Body); Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(invoke, parameter); q.Expression = q.Expression.And(lambda); } return q; } /// <summary> /// 建立 Like ( 模糊 ) 查询条件 /// </summary> /// <typeparam name="T">实体</typeparam> /// <param name="q">动态查询条件创建者</param> /// <param name="property">属性</param> /// <param name="value">查询值</param> /// <returns></returns> public static IQueryBuilder<T> Like<T>(this IQueryBuilder<T> q, Expression<Func<T, string>> property, string value) { value = value.Trim(); if (!string.IsNullOrEmpty(value)) { var parameter = property.GetParameters(); var constant = Expression.Constant("%" + value + "%"); MethodCallExpression methodExp = Expression.Call(null, typeof(SqlMethods).GetMethod("Like", new Type[] { typeof(string), typeof(string) }), property.Body, constant); Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter); q.Expression = q.Expression.And(lambda); } return q; } 

 

 

1  之前的方法 


   string s = "80,81,83,82";

 

   int[] p = s.Split(',').Select(m=>Convert.ToInt32(m)).ToArray();

       
       
        public IQueryable<tbQuestions> SelectQuestions(int[] p)
        {
            var result = from s1 in db.tbQuestions
                         where p.Contains(s1.id) 
                         select s1;
            return result;
        }

 

 

补充:

 

 

 

你可能感兴趣的:(sql,list,String,null,lambda,LINQ)