[C#] Linq 动态条件查询

应用背景:以货品为例,在基础数据中配置货品的判断规则,要根据这个规则筛选出符合条件的集合。

创建货品类

    public class Product
    {
        public string Name { get; set; }
        public string Code { get; set; }
        public string Unit { get; set; }
    }

主要实现方法

        public void GetProducts()
        {
            #region 创建List 实际应用从数据库中取值
            var products = new[] {
                new {Name = "货品1", Code = "001", Unit = "个"},
                new {Name = "货品2", Code = "002", Unit = "件"},
                new {Name = "货品3", Code = "003", Unit = "瓶"},
                new {Name = "货品4", Code = "004", Unit = "个"},
                new {Name = "货品1", Code = "005", Unit = "台"},
            };
            List<Product> lsProducts = new List<Product>();
            foreach (var q in products)
            {
                Product product = new Product();
                product.Name = q.Name;
                product.Code = q.Code;
                product.Unit = q.Unit;
                lsProducts.Add(product);
            }
            #endregion
            //获取到的判断规则 判断规则为Code和Unit 其中Name为固定条件
            string condition = "Code,Unit";
            string[] arrayCondition = condition.Split(',');
            //查询结果
            List<Product> result = lsProducts.Where(a => Filter(a, arrayCondition, "货品1", "005", "")).ToList(); //0条
            //只需判断Code 其中Name为固定条件
            string condition2 = "Code";
            arrayCondition = condition2.Split(',');
            result = lsProducts.Where(a => Filter(a, arrayCondition, "货品1", "005", "")).ToList();//1条
            //没有判断规则 其中Name为固定条件
            string condition3 = "";
            arrayCondition = condition3.Split(',');
            result = lsProducts.Where(a => Filter(a, arrayCondition, "货品1", "005", "")).ToList();//2条
        }

        public bool Filter(Product product, string[] arrayCondition, string name, string code, string unti)
        {
            bool result = false;
            result = (product.Name == name)
                && (!arrayCondition.Contains("Code") ? true : product.Code == code)
                && (!arrayCondition.Contains("Unit") ? true : product.Unit == unti);
            return result;
        }

  

  

  

 

转载于:https://www.cnblogs.com/linhuide/p/7466052.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值