gpt4 book ai didi

c# - PredicateBuilder 多个 AND OR 的问题

转载 作者:行者123 更新时间:2023-11-30 22:39:51 24 4
gpt4 key购买 nike

我有一个关于 PredicateBuilder 的问题,我真的希望你能给我一些关于如何解决这个问题的建议。我将尝试对此进行解释。

我有一个案例,人们可以根据关键字搜索产品。每个关键字都属于一个关键字组,因此一些真实数据将是:

关键字组/关键字

类型 - 链/

类型 - 手链/

颜色 - 紫色/

颜色 - 绿色

现在我想要得到以下结果:

在每个不同的关键字组之间应该有一个 OR。在 KeywordGroup 中的每个不同的关键字之间应该有一个 AND。

例如,用户只想搜索颜色为紫色或绿色的手镯。

这个 PredicateBuilder 有可能吗?

这是我目前所拥有的:

================================

/// <summary>
/// Search for products
/// </summary>
/// <param name="itemsPerPage"></param>
/// <returns></returns>
public List<Product> SearchProducts(int from, int max, string sorting, List<Keyword> filter, out int totalitems) {
try {

var predicate = PredicateBuilder.True<Product>();
KeywordGroup previousKeywordGroup = null;
foreach (Keyword k in filter.OrderBy(g=>g.KeywordGroup.SortOrder)) {
if (previousKeywordGroup != k.KeywordGroup) {
previousKeywordGroup = k.KeywordGroup;

predicate = predicate.And(p => p.Keywords.Contains(k));
}
else
predicate = predicate.Or(p => p.Keywords.Contains(k));
}

var products = context.Products.AsExpandable().Where(predicate);

//var products = from p in context.Products
// from k in p.Keywords
// where filter.Contains(k)
// select p;

totalitems = products.Distinct().Count();
if (sorting == "asc")
return products.Where(x => x.Visible == true).Distinct().Skip(from).Take(max).OrderBy(o => o.SellingPrice).ToList();
else
return products.Where(x => x.Visible == true).Distinct().Skip(from).Take(max).OrderByDescending(o => o.SellingPrice).ToList();
}
catch (Exception ex) {
throw ex;
}
}

================================

虽然它不起作用。

你能帮帮我吗?

谢谢!丹尼尔

最佳答案

您需要在循环中为每个关键字使用一个临时变量。来自Predicate Builder page :

The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop.

试试这个:

foreach (Keyword k in filter.OrderBy(g=>g.KeywordGroup.SortOrder)) {
Keyword temp = k;
if (previousKeywordGroup != k.KeywordGroup) {
previousKeywordGroup = k.KeywordGroup;

predicate = predicate.And(p => p.Keywords.Contains(temp));
}
else
predicate = predicate.Or(p => p.Keywords.Contains(temp));
}

请注意在使用谓词 AndOr 的每一行中使用 temp

关于c# - PredicateBuilder 多个 AND OR 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com