gpt4 book ai didi

c# - 如何根据用户输入动态构建和返回 linq 谓词

转载 作者:太空狗 更新时间:2023-10-29 18:07:51 27 4
gpt4 key购买 nike

有点卡在这上面了。基本上我有一个方法,我想返回一个谓词表达式,我可以将其用作 Where 条件。我认为我需要做的与此类似:http://msdn.microsoft.com/en-us/library/bb882637.aspx但我对我需要做什么有点困惑。

方法:

private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year)
{
if (!String.IsNullOrEmpty(keyword))
{
// Want the equivilent of .Where(x => (x.Title.Contains(keyword) || x.Description.Contains(keyword)));
}
if (venueId.HasValue)
{
// Some other predicate added...
}

return ??

}

示例用法:

var predicate = GetSearchPreducate(a,b,c,d);
var x = Conferences.All().Where(predicate);

我需要这种分离,以便我可以将我的谓词传递到我的存储库中并在其他地方使用它。

最佳答案

谓词只是一个返回 bool 值的函数。

我现在无法测试它,但这行不通吗?

private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year)
{
if (!String.IsNullOrEmpty(keyword))
{
//return a filtering fonction
return (conf)=> conf.Title.Contains(keyword) || Description.Contains(keyword)));
}
if (venueId.HasValue)
{
// Some other predicate added...
return (conf)=> /*something boolean here */;
}

//no matching predicate, just return a predicate that is always true, to list everything
return (conf) => true;

}

编辑:基于马特的评论如果你想组成代表,你可以这样做

private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year)
{
Expression<Func<Conference, bool> keywordPred = (conf) => true;
Expression<Func<Conference, bool> venuePred = (conf) => true;
//and so on ...


if (!String.IsNullOrEmpty(keyword))
{
//edit the filtering fonction
keywordPred = (conf)=> conf.Title.Contains(keyword) || Description.Contains(keyword)));
}
if (venueId.HasValue)
{
// Some other predicate added...
venuePred = (conf)=> /*something boolean here */;
}

//return a new predicate based on a combination of those predicates
//I group it all with AND, but another method could use OR
return (conf) => (keywordPred(conf) && venuePred(conf) /* and do on ...*/);

}

关于c# - 如何根据用户输入动态构建和返回 linq 谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3932542/

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