[C#] Linq 动态条件查询

时间:2024-05-20 11:06:08

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

创建货品类

    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;
}