[英]C# - Dynamic linq from a condition list
我有兩節課:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Product> Product { get; set; }
}
public class Product
{
public string ProductNumber { get; set; }
public string ProductColor { get; set; }
}
還有一個例子:
Customer[] c = new Customer[]
{
new Customer()
{
FirstName = "FirstName1",
LastName = "LastName1",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor1",
ProductNumber = "11"
}
}
},
new Customer()
{
FirstName = "FirstName2",
LastName = "LastName2",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor2",
ProductNumber = "12"
}
}
}
};
我使用System.Dynamic.Linq
庫來過濾我的數組:
var filter = c.Where("FirstName == \\"FirstName1\\"").Select(x => x).ToList();
我創建了一個類condition
和一個實例:
public class condition
{
public string propertyName { get; set; }
public string propertyValue { get; set; }
}
List<condition> f = new List<condition>
{
new condition()
{
propertyName = "FirstName",
propertyValue = "FirstName1"
},
new condition()
{
propertyName = "Product.ProductColor",
propertyValue = "11"
}
};
我想從這個List<Condition>
創建多個子句Where
這個怎么做 ?
從我可以收集到的只是一個簡單的例子,你的名單上執行此操作? 除非我錯過了什么?
var query = f.Where(x => x.propertyName == "FirstName" && x.propertyValue == "FirstName1");
為了解決你的問題,我修改了你的條件類,如下所示:
客戶的條件可能包含產品條件列表:
public class Condition
{
public string propertyName { get; set; }
public string propertyValue { get; set; }
public ICollection<Condition> Conditions { get; set; }
}
要創建它:
List<Condition> f = new List<Condition>
{
new Condition()
{
propertyName = "FirstName",
propertyValue = "FirstName1",
Conditions = new List<Condition>
{
new Condition
{
propertyName = "ProductColor",
propertyValue = "11"
}
}
},
};
現在您可以使用以下查詢過濾客戶和具有給定條件的產品:
var filteredCustomers =
from condition in f
from custmer in c
from product in custmer.Product
let propertyName = condition.propertyName
let propertyValue = condition.propertyValue
where (nameof(custmer.FirstName) == propertyName && custmer.FirstName == propertyValue)
&&
(condition.Conditions.Any(p => p.propertyName == nameof(product.ProductColor))
&& condition.Conditions.Any(p => p.propertyValue == product.ProductNumber))
select custmer;
foreach (var filterCustmer in filteredCustomers.Distinct())
{
Console.WriteLine(filterCustmer.FirstName);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.