好吧,伙计们,这没有意义......
我有这个方法:
// break down the search terms in to individual keywords
string[] searchTerms = ui_txtSearch.Text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
// get the complete list of companies
List<Company> results = Company.List();
// foreach keyword
for (int i = 0; i < searchTerms.Length; i++)
{
// results = the existing result set - the items that dont meet the current search term results.
results = (from comp in results
where comp.Name.Contains(searchTerms[i]
select comp).ToList();
}
现在的总体思路是,从公司列表中,我希望所有公司都包含我在 ui 上的文本框中提供的搜索词中的所有关键字。
我的问题是这个“包含”(上面在 ** 中突出显示)...如果我在名称字符串中说“公司”并搜索“Co”,我希望结果是这样,因为名称会包含那个但它不...
有什么想法吗?
编辑:
好的,我发现问题是区分大小写,所以我将代码重构为:
// break down the search terms in to individual keywords
string[] searchTerms = ui_txtSearch.Text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
// get the complete list of companies
List<Company> results = Company.List();
// foreach keyword
for (int i = 0; i < searchTerms.Length; i++)
{
// results = the existing result set - the items that dont meet the current search term results.
results = (
from comp in results
where comp.Name.ToLower().IndexOf(searchTerms[i].ToLower()) > -1
select comp
).ToList();
}
为了解决您的以下一些反馈:
搜索词可能类似于“测试公司 1”,我要查找公司名称中可以找到“测试”和“公司”和“1”的所有结果,结果集必须包含所有搜索关键字当完整的搜索词被“”分割时显示。
按照我的理解,最简洁的方法是使用循环??? ...还是我错了?
所以我基本上将其解读为...
- 获取所有公司的列表
- 按搜索词 1 过滤列表
- 从过滤列表中按搜索词 N 过滤 ... 并重复直到所有词都被考虑在内。
- 结果集现在将包含公司名称中提供的所有搜索词。
当前的代码似乎可以工作,并且在某种程度上回答了我的问题……但是你们认为有更有效的方法吗?
感谢大家的帮助:)
编辑 2:
感谢下面给出的所有帮助,我相信最终版本(仍在测试中)应该是这样的:
// break down the search terms in to individual keywords
string[] searchTerms = ui_txtSearch.Text.ToLower().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
// get the complete list of companies
List<Company> results;
// results = the existing result set - the items that dont meet the current search term results.
results = (
from comp in Company.List()
where searchTerms.All(s => comp.Name.ToLower().IndexOf(s) > -1)
select comp
).ToList();
谢谢大家:)
最佳答案
您要在每次迭代时重新分配 results
。但在我看来你也可以用这个替换你的整个代码:
string[] searchTerms = ui_txtSearch.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var results = (from comp in Company.List()
where searchTerms.All(s => comp.Contains(s))
select comp).ToList();
这应该更符合您的要求。
关于c# - 使用 contains 搜索 linq 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5274884/