感谢您阅读我的博客,如果您现在工作、学习累了或者疲惫了,不妨聆听一下音乐,它能够减轻你的疲劳,还能够带给您一种舒适愉悦的心情。如果您认为这篇文章还不错或者有所收获,您可以在页面 右侧和底部 扫描二维码 打赏我,您的鼓励是我继续写作、分享的最大动力!

C#动态拼接Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace DynamicLinqDemo
{
    public class Person
    {
        public string Name { get; set; }
    }

    /// <summary>
    ///     动态拼接Linq
    ///     https://www.cnblogs.com/LifeDecidesHappiness/p/15270834.html
    ///     LDH @ 2021-9-15
    /// </summary>
    internal class Program
    {
        private static void Main()
        {
            Console.Title = "动态拼接Linq";

            DynamicLinq();

            Console.ReadKey();
        }

        /// <summary>
        ///     动态拼接Linq
        /// </summary>
        private static void DynamicLinq()
        {
            var listPeople = new List<Person>();
            var p = new Person { Name = "LDH" };
            listPeople.Add(p);

            Console.WriteLine("Person.Name = " + p.Name);
            PrintLine();

            var filterCondition = GetExpression<Person>("x", "Contains", "Name", "LD");
            Console.WriteLine("Contains 动态 Linq:" + filterCondition); //x => x.Name.Contains("LD")

            var expression = listPeople.Where(filterCondition.Compile());
            Console.WriteLine("Contains Count:" + expression.Count());
            PrintLine();

            var filterCondition2 = GetExpression<Person>("x", "StartsWith", "Name", "LD");
            Console.WriteLine("StartsWith 动态 Linq:" + filterCondition2); //x => x.Name.StartsWith("LD")

            var expression2 = listPeople.Where(filterCondition2.Compile());
            Console.WriteLine("StartsWith Count:" + expression2.Count());
            PrintLine();

            var filterCondition3 = GetExpression<Person>("x", "EndsWith", "Name", "LD");
            Console.WriteLine("EndsWith 动态 Linq:" + filterCondition3); //x => x.Name.EndsWith("LD")

            var expression3 = listPeople.Where(filterCondition3.Compile());
            Console.WriteLine("EndsWith Count:" + expression3.Count());
            PrintLine();

            var filterCondition4 = GetExpression<Person>("x", "Equals", "Name", "LDH");
            Console.WriteLine("Equals 动态 Linq:" + filterCondition4); //x => x.Name.Equals("LDH")

            var expression4 = listPeople.Where(filterCondition4.Compile());
            Console.WriteLine("Equals Count:" + expression4.Count());
            PrintLine();
        }


        /// <summary>
        ///     动态拼接Linq
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lambdaVariableName">Lambda变量名(eg: x,m,n,type)</param>
        /// <param name="operatorName">StartsWith,Contains,EndsWith</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="propertyValue">属性值</param>
        /// <returns>eg:x => x.Name.Contains("LD")</returns>
        private static Expression<Func<T, bool>> GetExpression<T>(string lambdaVariableName, string operatorName,
            string propertyName, string propertyValue)
        {
            var parameterExp = Expression.Parameter(typeof(T), lambdaVariableName);
            var propertyExp = Expression.Property(parameterExp, propertyName);

            var method = typeof(string).GetMethod(operatorName, new[] { typeof(string) });
            var someValue = Expression.Constant(propertyValue, typeof(string));

            var containsMethodExp = Expression.Call(propertyExp, method ?? throw new InvalidOperationException(), someValue);
            return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
        }

        /// <summary>
        ///     分割线
        /// </summary>
        private static void PrintLine()
        {
            Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        }
    }
}  
        /// <summary>
        ///     动态拼接Linq (属性值为 string 类型)
        ///     var myFilter = GetExpressionPropertyValueString<T>("x", "Contains", fieldName, fieldValue);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lambdaVariableName">Lambda变量名(eg: x,m,n,type)</param>
        /// <param name="operatorName">Equals,StartsWith,Contains,EndsWith</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="propertyValue">属性值(string类型)</param>
        /// <returns>eg:x => x.Name.Contains("LD")</returns>
        private static Expression<Func<T, bool>> GetExpressionPropertyValueString<T>(string lambdaVariableName, string operatorName,
            string propertyName, string propertyValue)
        {
            var parameterExp = Expression.Parameter(typeof(T), lambdaVariableName);
            var propertyExp = Expression.Property(parameterExp, propertyName);

            var method = typeof(string).GetMethod(operatorName, new[] {typeof(string)});
            var someValue = Expression.Constant(propertyValue, typeof(string));

            var containsMethodExp =
                Expression.Call(propertyExp, method ?? throw new InvalidOperationException(), someValue);
            return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
        }

        /// <summary>
        ///     动态拼接Linq (属性值为 int 类型)
        ///     var whereExpression = GetExpressionPropertyValueInt<T>("x", "Equals", fieldName, Convert.ToInt32(fieldValue));
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lambdaVariableName">Lambda变量名(eg: x,m,n,type)</param>
        /// <param name="operatorName">Equals</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="propertyValue">属性值(int类型)</param>
        /// <returns>eg:x => x.Age.Equals(18)</returns>
        private static Expression<Func<T, bool>> GetExpressionPropertyValueInt<T>(string lambdaVariableName, string operatorName,
            string propertyName, int propertyValue)
        {
            var parameterExp = Expression.Parameter(typeof(T), lambdaVariableName);
            var propertyExp = Expression.Property(parameterExp, propertyName);

            var method = typeof(int).GetMethod(operatorName, new[] { typeof(int) });
            var someValue = Expression.Constant(propertyValue, typeof(int));

            var containsMethodExp =
                Expression.Call(propertyExp, method ?? throw new InvalidOperationException(), someValue);
            return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
        }
posted @ 2021-09-15 09:33  Love In Winter  阅读(1037)  评论(0编辑  收藏  举报
作者: LifeDecidesHappiness
出处: http://www.cnblogs.com/LifeDecidesHappiness/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,否则保留追究法律责任的权利,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址 2468881301@qq.com  联系我,非常感谢。
踏实做一个为人民服务的搬运工!
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能,您的支持和鼓励是我继续写作、分享的最大动力!

点击关注不迷路,让我带你上高速!