dynamic linq
😋 dynamic linq
2022/6/5 10:25:37
➡️

动态查询

自建构建表达式树

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

// Define a parameter expression for the input parameter
ParameterExpression pe = Expression.Parameter(typeof(int), "x");

// Define a constant expression for the value 3
ConstantExpression ce = Expression.Constant(3);

// Define a binary expression for the greater-than operation
BinaryExpression be = Expression.GreaterThan(pe, ce);

// Create a lambda expression from the binary expression
Expression<Func<int, bool>> lambda = Expression.Lambda<Func<int, bool>>(be, pe);

// Execute the dynamic query using the lambda expression
IEnumerable<int> results = numbers.Where(lambda.Compile());

// Output the results
Console.WriteLine("Numbers greater than 3:");
foreach (int number in results)
{
    Console.WriteLine(number);
}

Linq.Dynamic 库的使用

using System;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;

// Define a list of integers
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

// Define the dynamic query expression
string expression = "x => x > 3";

// Execute the dynamic query using the Dynamic LINQ library
IEnumerable<int> results = numbers.AsQueryable().Where(expression);

// Output the results
Console.WriteLine("Numbers greater than 3:");
foreach (int number in results)
{
    Console.WriteLine(number);
}
👍🎉🎊