本文共 24942 字,大约阅读时间需要 83 分钟。
1 var query =2 db.Customers.3 Where("City = @0 and Orders.Count >= @1", "London", 10).4 OrderBy("CompanyName").5 Select("new(CompanyName as Name, Phone)");
1 public static LambdaExpression ParseLambda( 2 ParameterExpression[] parameters, Type resultType, 3 string expression, params object[] values); 4 5 public static LambdaExpression ParseLambda( 6 Type argumentType, Type resultType, 7 string expression, params object[] values); 8 9 public static Expression>10 ParseLambda (11 string expression, params object[] values);
1 ParameterExpression x = Expression.Parameter(typeof(int), "x");2 ParameterExpression y = Expression.Parameter(typeof(int), "y");3 LambdaExpression e = DynamicExpression.ParseLambda(4 new ParameterExpression[] { x, y }, null, "(x + y) * 2");
1 LambdaExpression e = DynamicExpression.ParseLambda(2 new ParameterExpression[] { x, y }, typeof(double), "(x + y) * 2");
1 LambdaExpression e = DynamicExpression.ParseLambda(2 typeof(Customer), typeof(bool),3 "City = @0 and Orders.Count >= @1",4 "London", 10);
1 Expression> e =2 DynamicExpression.ParseLambda (3 "City = @0 and Orders.Count >= @1",4 "London", 10);
1 public static Expression Parse(Type resultType, string expression,2 params object[] values);
1 ParameterExpression x = Expression.Parameter(typeof(int), "x");2 ParameterExpression y = Expression.Parameter(typeof(int), "y");3 Dictionarysymbols = new Dictionary ();4 symbols.Add("x", x);5 symbols.Add("y", y);6 Expression body = DynamicExpression.Parse(null, "(x + y) * 2", symbols);7 LambdaExpression e = Expression.Lambda(8 body, new ParameterExpression[] { x, y });
1 public static Type CreateClass(params DynamicProperty[] properties);2 3 public static Type CreateClass(IEnumerableproperties);
1 DynamicProperty[] props = new DynamicProperty[] {2 new DynamicProperty("Name", typeof(string)),3 new DynamicProperty("Birthday", typeof(DateTime)) };4 Type type = DynamicExpression.CreateClass(props);5 object obj = Activator.CreateInstance(type);6 t.GetProperty("Name").SetValue(obj, "Albert", null);7 t.GetProperty("Birthday").SetValue(obj, new DateTime(1879, 3, 14), null);8 Console.WriteLine(obj);
IQueryable Extension Methods
The System.Linq.Dynamic.DynamicQueryable class implements the following extension methods for dynamically querying objects that implement the IQueryable<T> interface.1 public static IQueryable Where(this IQueryable source, 2 string predicate, params object[] values); 3 4 public static IQueryableWhere (this IQueryable source, 5 string predicate, params object[] values); 6 7 public static IQueryable Select(this IQueryable source, 8 string selector, params object[] values); 9 10 public static IQueryable OrderBy(this IQueryable source,11 string ordering, params object[] values);12 13 public static IQueryable OrderBy (this IQueryable source,14 string ordering, params object[] values);15 16 public static IQueryable Take(this IQueryable source, int count);17 18 public static IQueryable Skip(this IQueryable source, int count);19 20 public static IQueryable GroupBy(this IQueryable source,21 string keySelector, string elementSelector, params object[] values);22 23 public static bool Any(this IQueryable source);24 25 public static int Count(this IQueryable source);
These methods correspond to their System.Linq.Queryable counterparts, except that they operate on IQueryable instead of IQueryable<T> and use strings instead of lambda expressions to express predicates, selectors, and orderings. IQueryable is the non-generic base interface for IQueryable<T>, so the methods can be used even when T isn’t known on beforehand, i.e. when the source of a query is dynamically determined. (Note that because a dynamic predicate or ordering does not affect the result type, generic overloads are provided for Where and OrderBy in order to preserve strong typing when possible.)
The predicate, selector, ordering, keySelector, and elementSelector parameters are strings containing expressions written in the expression language. In the expression strings, the members of the current instance are automatically in scope and the instance itself can be referenced using the keyword it. The OrderBy mthod permits a sequence of orderings to be specified, separated by commas. Each ordering may optionally be followed by asc or ascending to indicate ascending order, or desc or descending to indicate descending order. The default order is ascending. The example1 products.OrderBy("Category.CategoryName, UnitPrice descending");
orders a sequence of products by ascending category name and, within each category, descending unit price.
The ParseException Class The Dynamic Expression API reports parsing errors using the System.Linq.Dynamic.ParseException class. The Position property of the ParseException class gives the character index in the expression string at which the parsing error occurred. Expression Language The expression language implemented by the Dynamic Expression API provides a simple and convenient way of writing expressions that can be parsed into LINQ expression trees. The language supports most of the constructs of expression trees, but it is by no means a complete query or programming language. In particular, the expression language does not support statements or declarations. The expression language is designed to be familiar to C#, VB, and SQL users. For this reason, some operators are present in multiple forms, such as && and and. Identifiers An Identifier consists of a letter or underscore followed by any number of letters, digits, or underscores. In order to reference an identifier with the same spelling as a keyword, the identifier must be prefixed with a single @ character. Some examples of identifiers: x Hello m_1 @true @String Identifiers of the from @x, where x is an integral number greater than or equal to zero, are used to denote the substitution values, if any, that were passed to the expression parser. For example: Casing is not significant in identifiers or keywords. Literals The expression language supports integer, real, string, and character literals. An integer literal consists of a sequence of digits. The type of an integer literal is the first of the types Int32, UInt32, Int64, or UInt64 that can represent the given value. An integer literal implicitly converts to any other numeric type provided the number is in the range of that type. Some examples of integer literals: 0 123 10000 A real literal consists of an integral part followed by a fractional part and/or an exponent. The integral part is a sequence of one or more digits. The fractional part is a decimal point followed by one or more digits. The exponent is the letter e or E followed by an optional + or – sign followed by one or more digits. The type of a real literal is Double. A real literal implicitly converts to any other real type provided the number is in the range of that type. Some examples of real literals: 1.0 2.25 10000.0 1e0 1e10 1.2345E-4 A string literal consists of zero or more characters enclosed in double quotes. Inside a string literal, a double quote is written as two consecutive double quotes. The type of a string literal is String. Some examples of string literals: "hello" "" """quoted""" "'" A character literal consists of a single character enclosed in single quotes. Inside a character literal, a single quote is written as two consecutive single quotes. The type of a character literal is Char. Some examples of character literals: 'A' '1' '''' '"' Constants The predefined constants true and false denote the two values of the type Boolean. The predefined constant null denotes a null reference. The null constant is of type Object, but is also implicitly convertible to any reference type. Types The expression language defines the following primitive types: Object Boolean Char String SByte Byte Int16 UInt16 Int32 UInt32 Int64 UInt64 Decimal Single Double DateTime TimeSpan Guid The primitive types correspond to the similarly named types in the System namespace of the .NET Framework Base Class Library. The expression language also defines a set of accessible types consisting of the primitive types and the following types from the System namespace: Math Convert The accessible types are the only types that can be explicitly referenced in expressions, and method invocations in the expression language are restricted to methods declared in the accessible types. The nullable form of a value type is referenced by writing a ? after the type name. For example, Int32? denotes the nullable form of Int32. The non-nullable and nullable forms of the types SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, and UInt64 are collectively called the integral types. The non-nullable and nullable forms of the types Single, Double, and Decimal are collectively called the real types. The integral types and real types are collectively called the numeric types. Conversions The following conversions are implicitly performed by the expression language: From the the null literal to any reference type or nullable type. From an integer literal to an integral type or real type provided the number is within the range of that type. From a real literal to a real type provided the number is within the range of that type. From a string literal to an enum type provided the string literal contains the name of a member of that enum type. From a source type that is assignment compatible with the target type according to the Type.IsAssignableFrom method in .NET. From a non-nullable value type to the nullable form of that value type. From a numeric type to another numeric type with greater range. The expression language permits explicit conversions using the syntax type(expr), where type is a type name optionally followed by ? and expr is an expression. This syntax may be used to perform the following conversions: Between two types provided Type.IsAssignableFrom is true in one or both directions. Between two types provided one or both are interface types. Between the nullable and non-nullable forms of any value type. Between any two types belonging to the set consisting of SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Decimal, Single, Double, Char, any enum type, as well as the nullable forms of those types. Operators The table below shows the operators supported by the expression language in order of precedence from highest to lowest. Operators in the same category have equal precedence. In the table, x, y, and z denote expressions, T denotes a type, and m denotes a member. Category Expression Description Primary x.m Instance field or instance property access. Any public field or property can be accessed x.m(…) Instance method invocation. The method must be public and must be declared in an accessible type. x[…] Array or indexer access. Multi-dimensional arrays are not supported. T.m Static field or static property access. Any public field or property can be accessed. T.m(…) Static method invocation. The method must be public and must be declared in an accessible type. T(…) Explicit conversion or constructor invocation. Note that new is not required in front of a constructor invocation. new(…) Data object initializer. This construct can be used to perform dynamic projections Current instance. In contexts where members of a current object are implicitly in scope, it is used to refer to the entire object itself. x(…) Dynamic lambda invocation. Used to reference another dynamic lambda expression. iif(x, y, z) Conditional expression. Alternate syntax for x ? y : z. Unary -x Negation. Supported types are Int32, Int64, Decimal, Single, and Double. !x not x Logical negation. Operand must be of type Boolean. Multiplicative x * y Multiplication. Supported types are Int32, UInt32, Int64, UInt64, Decimal, Single, and Double. x / y Division. Supported types are Int32, UInt32, Int64, UInt64, Decimal, Single, and Double. x % y x mod y Remainder. Supported types are Int32, UInt32, Int64, UInt64, Decimal, Single, and Double. Additive x + y Addition or string concatenation. Performs string concatenation if either operand is of type String. Otherwise, performs addition for the supported types Int32, UInt32, Int64, UInt64, Decimal, Single, Double, DateTime, and TimeSpan. x – y Subtraction. Supported types are Int32, UInt32, Int64, UInt64, Decimal, Single, Double, DateTime, and TimeSpan. x & y String concatenation. Operands may be of any type. Relational x = y x == y Equal. Supported for reference types and the primitive types. Assignment is not supported. x != y x <> y Not equal. Supported for reference types and the primitive types. x < y Less than. Supported for all primitive types except Boolean, Object and Guid. x > y Greater than. Supported for all primitive types except Boolean, Object and Guid. x <= y Less than or equal. Supported for all primitive types except Boolean, Object and Guid. x >= y Greater than or equal. Supported for all primitive types except Boolean, Object and Guid. Logical AND x && y x and y Logical AND. Operands must be of type Boolean. Logical OR x || y x or y Logical OR. Operands must be of type Boolean. Conditional x ? y : z Evaluates y if x is true, evaluates z if x is false. Method and Constructor Invocations The expression language limits invocation of methods and constructors to those declared public in the accessible types. This restriction exists to protect against unintended side effects from invocation of arbitrary methods. The expression language permits getting (but not setting) the value of any reachable public field, property, or indexer. Overload resolution for methods, constructors, and indexers uses rules similar to C#. In informal terms, overload resolution will pick the best matching method, constructor, or indexer, or report an ambiguity error if no single best match can be identified. Note that constructor invocations are not prefixed by new. The following example creates a DateTime instance for a specfic year, month, and day using a constructor invocation: orders.Where("OrderDate >= DateTime(2007, 1, 1)"); Data Object Initializers A data object initializer creates a data class and returns an instance of that class. The properties of the data class are inferred from the data object initializer. Specifically, a data object initializer of the form new(e1 as p1, e2 as p2, e3 as p3) creates a data class with three properties, p1, p2, and p3, the types of which are inferred from the expressions e1, e2, and e3, and returns an instance of that data class with the properties initialized to the values computed by e1, e2, and e3. A property initializer may omit the as keyword and the property name provided the associated expression is a field or property access. The example customers.Select("new(CompanyName as Name, Phone)"); creates a data class with two properties, Name and Phone, and returns a sequence of instances of that data class initialized from the CompanyName and Phone properties of each customer. Current Instance When parsing a lambda expression with a single unnamed parameter, the members of the unnamed parameter are automatically in scope in the expression string, and the current instance given by the unnamed parameter can be referenced in whole using the keyword it. For example, customers.Where("Country = @0", country); is equivalent to customers.Where("it.Country = @0", country); The IQueryable extension methods all parse their expression arguments as lambda expressions with a single unnamed parameter. Dynamic Lambda Invocation An expression can reference other dynamic lambda expressions through dynamic lambda invocations. A dynamic lambda invocation consists of a substitution variable identifier that references an instance of System.Linq.Expressions.LambdaExpression, followed by an argument list. The arguments supplied must be compatible with the parameter list of the given dynamic lambda expression. The following parses two separate dynamic lambda expressions and then combines them in a predicate expression through dynamic lambda invocations: Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("City = \"London\""); Expression<Func<Customer, bool>> e2 = DynamicExpression.ParseLambda<Customer, bool>("Orders.Count >= 10"); IQueryable<Customer> query = db.Customers.Where("@0(it) and @1(it)", e1, e2); It is of course possible to combine static and dynamic lambda expressions in this fashion: Expression<Func<Customer, bool>> e1 = c => c.City == "London"; Expression<Func<Customer, bool>> e2 = DynamicExpression.ParseLambda<Customer, bool>("Orders.Count >= 10"); IQueryable<Customer> query = db.Customers.Where("@0(it) and @1(it)", e1, e2); The examples above both have the same effect as: IQueryable<Customer> query = db.Customers.Where(c => c.City == "London" && c.Orders.Count >= 10); operators A subset of the Standard Query Operators is supported for objects that implement IEnumerable<T>. Specifically, the following constructs are permitted, where seq is an IEnumerable<T> instance, predicate is a boolean expression, and selector is an expression of any type: seq . Where ( predicate ) seq . Any ( ) seq . Any ( predicate ) seq . All ( predicate ) seq . Count ( ) seq . Count ( predicate ) seq . Min ( selector ) seq . Max ( selector ) seq . Sum ( selector ) seq . Average ( selector ) In the predicate and selector expressions, the members of the current instance for that sequence operator are automatically in scope, and the instance itself can be referenced using the keyword it. An example: customers.Where("Orders.Any(Total >= 1000)"); Enum type support The expression language supports an implicit conversion from a string literal to an enum type provided the string literal contains the name of a member of that enum type. For example,1 orders.Where("OrderDate.DayOfWeek = \"Monday\"");2 3 //is equivalent to4 5 orders.Where("OrderDate.DayOfWeek = @0", DayOfWeek.Monday);
本文转自博客园张占岭(仓储大叔)的博客,原文链接:,如需转载请自行联系原博主。