gpt4 book ai didi

c# - PredicateBuilder 的问题

转载 作者:行者123 更新时间:2023-11-30 14:02:21 24 4
gpt4 key购买 nike

我在使用 PredicateBuilder 将“Or Where”子句动态添加到 LINQ 语句时遇到问题。我将首先解释我要实现的目标。

我有一个倒排索引,用于存储来自一堆链接标题的关键字。我正在使用一个,因此我可以根据这些关键字快速搜索这些链接。倒排索引是类型

Dictionary<string, List<VerifiedUrl>>

所以基本上每个词都与包含该词的 URL 列表相关联。

我的下一阶段是使倒排索引可搜索。因此,当我搜索“the blue”时,我返回了与键“the”或“blue”关联的所有链接。经过几次 Google 搜索后,向 LINQ 语句动态添加“Or Where”子句的最佳方式似乎是通过 PredicateBuilder类(class)。我在使用我构建的谓词的最后一步时遇到了问题。

var invertedIndex = new Dictionary<string, List<VerifiedUrl>>();

//the invertedIndex is built and filled here. Now I am trying to search through it.

Console.WriteLine("\nEnter words to see if there are matches");
string query = Console.ReadLine();
Console.WriteLine();

string[] words = query.Split(',', ' ');

//the predicate I'll be building. I'm not positive it is of the correct type. I've assumed that it should be of the same type as the Dictionary type in the inverted index
var predicate = PredicateBuilder.False<KeyValuePair<string, List<VerifiedUrl>>>();

foreach (string w in words)
{
string temp = w;
predicate = predicate.Or(p => p.Key == temp);
}
//this is the line that generates the syntax error.
test = invertedIndex.Where(predicate);

我在 .Where 语句中遇到错误。将鼠标悬停在 .Where 上会显示“无法从用法中推断出类型参数。请尝试准确指定类型参数。”

我尝试改变:

var predicate = PredicateBuilder.False<KeyValuePair<string, List<VerifiedUrl>>>();

Expression<Func<KeyValuePair<string, List<VerifiedUrl>>, bool>> predicate = PredicateBuilder.False<KeyValuePair<string, List<VerifiedUrl>>>();

但这没有任何效果。在错误控制台中,我实际上得到了不同的错误:

Error   1   Instance argument: cannot convert from 'System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<InvertedIndexConsoleApp.VerifiedUrl>>' to 'System.Linq.IQueryable<System.Collections.Generic.KeyValuePair<string,System.Collections.Generic.List<InvertedIndexConsoleApp.VerifiedUrl>>>'   c:\users\josh\documents\visual studio 2010\Projects\InvertedIndexConsoleApp\InvertedIndexConsoleApp\Program.cs  79  25  InvertedIndexConsoleApp

Error 2 'System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<InvertedIndexConsoleApp.VerifiedUrl>>' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,bool>>)' has some invalid arguments c:\users\josh\documents\visual studio 2010\Projects\InvertedIndexConsoleApp\InvertedIndexConsoleApp\Program.cs 79 25 InvertedIndexConsoleApp

最佳答案

.Where 参数必须是 Func,但 PredicateBuilder.Or 返回 Expression< Func<..>> 的问题。试试这个

test = invertedIndex.Where(predicate.Compile());

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

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