ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【NetCore】使用表达式目录树实现动态组装Linq表达式

2021-10-17 16:02:09  阅读:163  来源: 互联网

标签:Code Name NetCore Age Linq var new public 表达式


使用表达式目录树实现动态组装Linq表达式

写在前面

  • 自己开发中遇到的问题,在提供多参数查询列表时,有时候需要写大量的 ifwhere 的Linq表达式
  • 查询参数在特性里配置实体的名字这个参数,尚未使用到。
  • 趁着代码量还不多,做一下记录,给将来自己提供便利的同时,也方便别人。

1. 定义 目标实体 类型(例:Student)

public class Student
{
    public string Name { get; set; }
    public string Code { get; set; }
    public int? Age { get; set; }
}

2. 定义 查询参数 类型

// 这里使用与目标实体类型一致的属性
// 后面需要考虑在特性提供字段名,防止耦合太大
public class StudentListQueryParameter
{
    [Where(Type = WhereTypeEnum.Like, Field = nameof(Name))]
    public string Name { get; set; }

    [Where(Type = WhereTypeEnum.Like, Field = nameof(Code))]
    public string Code { get; set; }

    [Where(Type = WhereTypeEnum.Equal, Field = nameof(Age))]
    public int? Age { get; set; }
}

3. 定义 WhereAttribute 特性,用于设置 对比类型字段名

  • 枚举类型
public enum WhereTypeEnum
{
    [UserDescription(Description = "等于")]
    Equal = 0,
    [UserDescription(Description = "大于")]
    Larger = 11,
    [UserDescription(Description = "大于等于")]
    LargerEqual = 12,
    [UserDescription(Description = "小于")]
    Less = 21,
    [UserDescription(Description = "小于等于")]
    LessEqual = 22,
    [UserDescription(Description = "相似")]
    Like = 31,
    [UserDescription(Description = "包含")]
    In = 32,
}

// 不是必要的
public static class UserDescriptionAttributeExtensions
{
    public static string GetUserDescription<EnumType>
        (this EnumType @enum) where EnumType:Enum
    {
        var member = typeof(WhereTypeEnum)
            .GetMember(@enum.ToString())
            .FirstOrDefault();
        var attr = member?.GetCustomAttribute<UserDescriptionAttribute>();
        return attr?.Description;
    }
}
  • 查询参数特性

/// <summary>
/// 查询参数特性
/// </summary>
/// <remarks>
/// 允许给属性添加,允许多次添加,不可继承
/// </remarks>
[AttributeUsage( AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class WhereAttribute : Attribute
{
    /// <summary>
    /// 实体属性名
    /// </summary>
    public string Field { get; set; }

    /// <summary>
    /// 对比类型
    /// </summary>
    public WhereTypeEnum Type { get; set; } 
}

IQueryable<TEnity> 拓展方法

 public class BuildWhereOptions
 {
     public StringComparison StringComparison { get; set; } = default;
     public WhereAttribute DefaultAttribute { get; set; } = null;
 }
public static class IQuaryableExtension
{
    /// <summary>
    /// 生成查询条件
    /// </summary>
    /// <typeparam name="TQueryParams">查询参数对象</typeparam>
    /// <param name="queryable">原有IQueryable</param>
    /// <returns>lambda 表达式</returns>
    public static Expression<Func<TEntity, bool>> BuildWhere<TEntity, TQueryParams>(this IQueryable<TEntity> query, TQueryParams input, Action<BuildWhereOptions> options = null) where TEntity : class
    {
        // 配置项
        BuildWhereOptions buildWhereOptions = new();
        if (options is not null)
        {
            options(buildWhereOptions);
        }

        var t = Expression.Parameter(typeof(TEntity), "t");
        var trueExpression = Expression.Constant(true);
        var resultExpression = Expression.AndAlso(trueExpression, trueExpression);

        // 遍历入参所有属性
        var queryParamProps = typeof(TQueryParams).GetProperties();
        foreach (var prop in queryParamProps)
        {
            // 根据特性分别处理
            var attr = prop.GetCustomAttribute<WhereAttribute>();

            // 默认判断是否相等
            if (attr is null)
            {
                attr = buildWhereOptions.DefaultAttribute;
                if (attr is null)
                {
                    continue;
                }
            }

            var entityProperty = Expression.Property(t, prop.Name);
            var v = prop.GetValue(input);
            if (v is null)
            {
                continue;
            }
            var paramValue = Expression.Constant(v, prop.PropertyType);
            switch (attr.Type)
            {
                case WhereTypeEnum.Equal:
                    // t.Name==value;   
                    var p = Expression.Convert(paramValue, entityProperty.Type);
                    var equalExpression = Expression.Equal(entityProperty, p);
                    resultExpression = Expression.AndAlso(resultExpression, equalExpression);

                    break;
                case WhereTypeEnum.Larger:
                    break;
                case WhereTypeEnum.LargerEqual:
                    break;
                case WhereTypeEnum.Less:
                    break;
                case WhereTypeEnum.LessEqual:
                    break;
                case WhereTypeEnum.Like:
                    // t.Name.Contains(value);
                    var containMethod = typeof(string).GetMethod(nameof(string.Contains), new Type[] { typeof(string), typeof(StringComparison) });
                    var stringComparisonValue = Expression.Constant(buildWhereOptions.StringComparison);
                    string s = v as string;
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        continue;
                    }
                    var containMethodExpression = Expression.Call(entityProperty, containMethod, paramValue, stringComparisonValue);
                    resultExpression = Expression.AndAlso(resultExpression, containMethodExpression);
                    break;
                case WhereTypeEnum.In:
                    break;
                default:
                    break;
            }
        }

        return Expression.Lambda<Func<TEntity, bool>>(resultExpression, t);
    }
}

模拟数据调用

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");

    var input = new StudentListQueryParameter()
    {
        // Age = null,
        Code = "A00",
        Name = "张"
    };

    List<Student> students = new List<Student> {
        new Student{ Code="A001",Name="张三",Age=25},
        new Student{ Code="A002",Name="李四",Age=21},
        new Student{ Code="A003",Name="王五",Age=10},
        new Student{ Code="B001",Name="张四",Age=31},
        new Student{ Code="B002",Name="李五",Age=12},
        new Student{ Code="B003",Name="王六",Age=45},
        new Student{ Code="C001",Name="张五",Age=22},
        new Student{ Code="C001",Name="李六",Age=18},
        new Student{ Code="C001",Name="王七",Age=20},
    };

    var query = students.AsQueryable();
    var result = query.Where(query.BuildWhere(input));

    //var result = query.Where(query.BuildWhere(input, options =>
    //{
    //    options.StringComparison = StringComparison.OrdinalIgnoreCase;
    //    options.DefaultAttribute = null;
    //}));
             
}

不同条件筛选结果展示

Example 1

var input = new StudentListQueryParameter()
{
    // Age = null,
    Code = "A00",
    Name = "张"
};
[
    {"Name":"张三","Code":"A001","Age":25}
]

Example 2

var input = new StudentListQueryParameter()
{
    // Age = null,
    Code = "A00",
    // Name = "张"
};
[
    {"Name":"张三","Code":"A001","Age":25},
    {"Name":"李四","Code":"A002","Age":21},
    {"Name":"王五","Code":"A003","Age":10}
]

Example 3

var input = new StudentListQueryParameter()
{
    // Age = null,
    // Code = "A00",
    Name = "张"
};
[
    {"Name":"张三","Code":"A001","Age":25},
    {"Name":"张四","Code":"B001","Age":31},
    {"Name":"张五","Code":"C001","Age":22}
]

参考

标签:Code,Name,NetCore,Age,Linq,var,new,public,表达式
来源: https://www.cnblogs.com/wosperry/p/15417132.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有