gpt4 book ai didi

c# - 使用 Linq 搜索任何单词

转载 作者:太空宇宙 更新时间:2023-11-03 20:58:11 27 4
gpt4 key购买 nike

在我的 winform 应用程序中,我有一个表单,用户可以在其中通过在搜索字段中键入任何文本来搜索产品。例如,产品描述可能存储为 "Adidas aftershave 100Ml" 。但用户可以键入任何内容,例如 100 Ml Aftershave。因此,我想使用 linq 进行查询,以获取描述中包含任何这些词 (100 Ml Aftershave) 的所有记录。

到目前为止,我已经做了这样的事情:

List<string>txtList =  txtSearchTerm.Text.Split(' ').ToList();
return dbContext.productRepo.Where(t => txtList.Any(b =>
t.ProductDescription.StartsWith(b)
|| t.ProductDescription.EndsWith(b)
|| t.ProductDescription.Contains(b)

)).Select(x => x.ProductDescription).ToList();

以更好的方式实现此目的的任何其他方式,使其更快或任何其他改进。

谢谢

最佳答案

好吧,您正在测试描述是否开始、结束并包含某些内容。前两个已经是多余的,因为 Contains“包含”了它们:

var matchingDescriptions = dbContext.productRepo
.Where(x => txtList.Any(x.ProductDescription.Contains))
.Select(x => x.ProductDescription));

另一个简单的优化(对于 Linq-To-Objects),我会先按长度对单词进行排序:

var txtList = txtSearchTerm.Text.Split(' ').OrderBy(s => s.Length).ToList()

关于c# - 使用 Linq 搜索任何单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48227727/

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