DynamicQueryable基于Linq的动态查询

本文介绍了DynamicQueryable,这是一个针对Linq的扩展,用于增强动态查询能力。作者分享了相关教程链接,旨在帮助开发者更好地理解和使用这个库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

DynamicQueryable是老外对Linq动态查询的一个扩展

    public static class DynamicQueryable    {        public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)        {            return (IQueryable<T>)Where((IQueryable)source, predicate, values);        }        public static IQueryable Where(this IQueryable source, string predicate, params object[] values)        {            if (source == null) throw new ArgumentNullException("source");            if (predicate == null) throw new ArgumentNullException("predicate");            LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);            return source.Provider.CreateQuery(                Expression.Call(                    typeof(Queryable), "Where",                    new Type[] { source.ElementType },                    source.Expression, Expression.Quote(lambda)));        }        public static IQueryable Select(this IQueryable source, string selector, params object[] values)        {            if (source == null) throw new ArgumentNullException("source");            if (selector == null) throw new ArgumentNullException("selector");            LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);            return source.Provider.CreateQuery(                Expression.Call(                    typeof(Queryable), "Select",                    new Type[] { source.ElementType, lambda.Body.Type },                    source.Expression, Expression.Quote(lambda)));        }        public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values)        {            return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);        }        public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values)        {            if (source == null) throw new ArgumentNullException("source");            if (ordering == null) throw new ArgumentNullException("ordering");            ParameterExpression[] parameters = new ParameterExpression[] {                Expression.Parameter(source.ElementType, "") };            ExpressionParser parser = new ExpressionParser(parameters, ordering, values);            IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();            Expression queryExpr = source.Expression;            string methodAsc = "OrderBy";            string methodDesc = "OrderByDescending";            foreach (DynamicOrdering o in orderings)            {                queryExpr = Expression.Call(                    typeof(Queryable), o.Ascending ? methodAsc : methodDesc,                    new Type[] { source.ElementType, o.Selector.Type },                    queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));                methodAsc = "ThenBy";                methodDesc = "ThenByDescending";            }            return source.Provider.CreateQuery(queryExpr);        }        public static IQueryable Take(this IQueryable source, int count)        {            if (source == null) throw new ArgumentNullException("source");            return source.Provider.CreateQuery(                Expression.Call(                    typeof(Queryable), "Take",                    new Type[] { source.ElementType },                    source.Expression, Expression.Constant(count)));        }        public static IQueryable Skip(this IQueryable source, int count)        {            if (source == null) throw new ArgumentNullException("source");            return source.Provider.CreateQuery(                Expression.Call(                    typeof(Queryable), "Skip",                    new Type[] { source.ElementType },                    source.Expression, Expression.Constant(count)));        }        public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)        {            if (source == null) throw new ArgumentNullException("source");            if (keySelector == null) throw new ArgumentNullException("keySelector");            if (elementSelector == null) throw new ArgumentNullException("elementSelector");            LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);            LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);            return source.Provider.CreateQuery(                Expression.Call(                    typeof(Queryable), "GroupBy",                    new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },                    source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));        }        public static bool Any(this IQueryable source)        {            if (source == null) throw new ArgumentNullException("source");            return (bool)source.Provider.Execute(                Expression.Call(                    typeof(Queryable), "Any",                    new Type[] { source.ElementType }, source.Expression));        }        public static int Count(this IQueryable source)        {            if (source == null) throw new ArgumentNullException("source");            return (int)source.Provider.Execute(                Expression.Call(                    typeof(Queryable), "Count",                    new Type[] { source.ElementType }, source.Expression));        }    }    public abstract class DynamicClass    {        public override string ToString()        {            PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);            StringBuilder sb = new StringBuilder();            sb.Append("{");            for (int i = 0; i < props.Length; i++)            {                if (i > 0) sb.Append(", ");                sb.Append(props[i].Name);                sb.Append("=");                sb.Append(props[i].GetValue(this, null));            }            sb.Append("}");            return sb.ToString();        }    }    public class DynamicProperty    {        string name;        Type type;        public DynamicProperty(string name, Type type)        {            if (name == null) throw new ArgumentNullException("name");            if (type == null) throw new ArgumentNullException("type");            this.name = name;            this.type = type;        }        public string Name        {            get { return name; }        }        public Type Type        {            get { return type; }        }    }    public static class DynamicExpression    {        public static Expression Parse(Type resultType, string expression, params object[] values)        {            ExpressionParser parser = new ExpressionParser(null, expression, values);            return parser.Parse(resultType);        }        public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values)        {            return ParseLambda(new ParameterExpression[] { Expression.Parameter(itType, "") }, resultType, expression, values);        }        public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values)        {            ExpressionParser parser = new ExpressionParser(parameters, expression, values);            return Expression.Lambda(parser.Parse(resultType), parameters);        }        public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values)        {            return (Expression<Func<T, S>>)ParseLambda(typeof(T), typeof(S), expression, values);        }        public static Type CreateClass(params DynamicProperty[] properties)        {            return ClassFactory.Instance.GetDynamicClass(properties);        }        public static Type CreateClass(IEnumerable<DynamicProperty> properties)        {            return ClassFactory.Instance.GetDynamicClass(properties);        }    }    internal class DynamicOrdering    {        public Expression Selector;        public bool Ascending;    }    internal class Signature : IEquatable<Signature>    {        public DynamicProperty[] properties;        public int hashCode;        public Signature(IEnumerable<DynamicProperty> properties)        {            this.properties = properties.ToArray();            hashCode = 0;            foreach (DynamicProperty p in properties)            {                hashCode ^= p.Name.GetHashCode() ^ p.Type.GetHashCode();            }        }        public override int GetHashCode()        {            return hashCode;        }        public override bool Equals(object obj)        {            return obj is Signature ? Equals((Signature)obj) : false;        }        public bool Equals(Signature other)        {            if (properties.Length != other.properties.Length) return false;            for (int i = 0; i < properties.Length; i++)            {                if (properties[i].Name != other.properties[i].Name ||                    properties[i].Type != other.properties[i].Type) return false;            }            return true;        }    }    internal class ClassFactory    {        public static readonly ClassFactory Instance = new ClassFactory();        static ClassFactory() { }  // Trigger lazy initialization of static fields        ModuleBuilder module;        Dictionary<Signature, Type> classes;        int classCount;        ReaderWriterLock rwLock;        private ClassFactory()        {            AssemblyName name = new AssemblyName("DynamicClasses");            AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);#if ENABLE_LINQ_PARTIAL_TRUST            new ReflectionPermission(PermissionState.Unrestricted).Assert();#endif            try   &n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值