Heim >Backend-Entwicklung >C++ >Kann die dynamische Linq -Bestellung auf 'Ienumerable' sowie auf 'IQueryable' angewendet werden?
Dynamisches linq orderBy on iEnumerable & lt; t & gt; / IQueryable & lt; t & gt;
In Dynamic Linq können Sie eine SQL-ähnliche Zeichenfolge (z. B. "OrderBy (" Name, Alter Desc ") verwenden, um die Ergebnisse zu bestellen. Die bisher verfügbaren Beispiele arbeiten jedoch nur mit iQueryable & lt; t & gt;. Dies wirft die Frage auf: Ist es möglich, diese Funktionalität auf iEnumerable & lt; t & gt;? Methoden, die asquerabel verwenden. Der folgende Code dient jedoch als die erforderliche Kernausdrucklogik:
Integration dynamischer Funktionalität
Für dynamische linq-to-Objects-Szenarien können Sie das System nutzen .Dynamisch für mehr Flexibilität.
public static IOrderedQueryable<T> OrderBy<T>( this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>( this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>( this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>( this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>( IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] { source, lambda }); return (IOrderedQueryable<T>)result; }
Das obige ist der detaillierte Inhalt vonKann die dynamische Linq -Bestellung auf 'Ienumerable' sowie auf 'IQueryable' angewendet werden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!