gpt4 book ai didi

c# - 使用c#(linq to sql)进行多关键字数据库搜索

转载 作者:行者123 更新时间:2023-11-30 17:53:39 25 4
gpt4 key购买 nike

我正在尝试构建一个接受多个关键字(空格分隔或逗号,这不是问题)的搜索。我现在有这个

public IQueryable<Post> Search(string criteria, int x)
{
return
(_db.Posts.Where(p => p.IsActive &&
(p.PostText.Contains(criteria) || p.Weather.Contains(criteria) || p.Location.Contains(criteria))
).OrderByDescending(p => p.PostDate)).Take(x);
}

但这只会返回完全匹配。我将如何搜索每个关键字并返回 x 个结果?顺便说一下,它应该是一个 OR。

谢谢

最佳答案

试试这个,我使用并行来加速搜索。我正在检查字符串 [] 匹配中传递的任何键的一系列字符串。在我的示例中,我正在搜索“test”和“1”,您将看到 3 个结果。

static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("b lue number 1");
list.Add("test number 234");
list.Add("yello number 2334");
list.Add("yes whippea number 324234");
list.Add("test number asdf");

var results = Program.Search(list,"test","1");

Console.ReadLine();
}

以您的示例为例,您可以执行类似的操作。

public List<Post> Search(string criteria, int x)
{
// Split all the search keys by space, so if you have "Search Word", you will get
// the occurances of [Search] and also [Word]
List<string> searchKeys = criteria.Split(' ').ToList<string>();

// Filter active
_db = _db.Where(p => p.IsActive);

// Go through each key
foreach (string str in searchKeys)
{
_db = _db.Where(p => p.Location.Contains(str)
|| p.PostText.Contains(str)
|| p.Weather.Contains(str));
}

// Return number wanted - and items will only be extracted here on the ToList()
return _db.OrderByDescending(p => p.PostDate).Take(x).ToList();
}

我正在循环条件并逐一添加条件。条件必须是您正在执行的搜索键的字符串,并且在空格之间分隔以获取所有匹配项。

关于c# - 使用c#(linq to sql)进行多关键字数据库搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076101/

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