使用PredicateBuilder(從LinqPad的作者),你可以建立從一組在編譯時不知道情況的查詢。下面列出的是足夠的:
var predicate = PredicateBuilder.True<Product>();
foreach (Suitability criteria in searchCriteria)
{
string tempKey = criteria.Key;
string tempValue = criteria.Value;
predicate = predicate.And(p =>
p.Items.Any(s => s.Key == tempKey && s.Value == tempValue));
}
return dataContext.Products.Where(predicate.Compile());
UPDATE:下面有我已經測試使用一個IEnumerable作爲源,將所得設定productsResult
包含所述第一和第二產品中products
列表,它的工作原理的一些示例代碼:
var searchCriteria = new List<Suitability>()
{
new Suitability() { Key="a", Value="b" },
new Suitability() { Key="a", Value="c" }
};
var products = new List<Product>()
{
new Product()
{
Items = new List<Suitability>() {
new Suitability() { Key="a", Value="b" },
new Suitability() { Key="a", Value="c" }}
},
new Product()
{
Items = new List<Suitability>() {
new Suitability() { Key="a", Value="b" },
new Suitability() { Key="a", Value="c" },
new Suitability() { Key="b", Value="c" }}
},
new Product()
{
Items = new List<Suitability>() {
new Suitability() { Key="c", Value="d" }}
}
};
var predicate = PredicateBuilder.True<Product>();
foreach (Suitability criteria in searchCriteria)
{
string tempKey = criteria.Key;
string tempValue = criteria.Value;
predicate = predicate.And(p => p.Items.Any(
s => s.Key == tempKey && s.Value == tempValue));
}
IEnumerable<Product> productsResult = products.Where(predicate.Compile());
@Simon,我試圖實現這一點,但後來我記得我沒有datacontext,因爲這不是LINQ to SQL,當我將它應用於我的IEnumerable列表時,我得到一個錯誤。錯誤\t方法'System.Linq.Enumerable.Where (System.Collections.Generic.IEnumerable ,System.Func )'的類型參數不能根據用法推斷。嘗試明確指定類型參數。 –
griegs
2010-03-11 02:19:58
@griegs add .Compile()將Func從表達式'predicate'中取出...我更新了我的答案。 – 2010-03-11 03:05:48
我改變了主意並選擇了這個作爲首選答案。作品感謝你。我仍然必須同意@Aaronaught使用EAV模型的方法並不理想,但是當您沒有其它選擇時... – griegs 2010-03-11 03:42:38