zoukankan      html  css  js  c++  java
  • [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;
            }
    

      

      

      

  • 相关阅读:
    模拟hadoop-rpc通信
    IOUtils方式上传下载文件
    HDFS基本操作的API
    HDFS基本命令行操作及上传文件的简单API
    gcj_2016_Round1_B
    hiho_1070_RMQ
    hiho_1068_RMQ_st算法
    hiho_1067_最近公共祖先2
    hiho_1062_最近公共祖先
    hiho_1066_并查集
  • 原文地址:https://www.cnblogs.com/linhuide/p/7466052.html
Copyright © 2011-2022 走看看