linq关键字搜索包含

时间:2011-03-11 15:31:49

标签: c# .net linq string

好的,这没有任何意义......

我有这个方法:

// 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上的文本框中提供的搜索词中的所有关键字。

我的问题是这个“包含”(在上面突出显示**)...如果我在名称字符串中说“公司”并且我搜索“公司”我希望它结果是因为名称会包含但不包含......

任何想法?

编辑:

好的,我发现问题是区分大小写的,所以我重构了这个代码:

// 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”,我正在查找所有结果,其中“test”和“company”和“1”可以在公司名称中找到,结果集必须包含所有搜索关键字当完整搜索词被“”分割时显示。

最简洁的方法是使用循环,因为我理解它? ......或者我错了?

所以我基本上把它读成......

  1. 获取所有公司的列表
  2. 按搜索字词1过滤列表
  3. 从过滤后的列表过滤按搜索字词N ...并重复,直到考虑所有字词。
  4. 结果集现在将包含公司名称中提供的所有搜索字词。
  5. 当前的代码似乎有效并且回答了我的问题......但是你们认为这是一种更有效的方法吗?

    感谢所有人的帮助:)

    编辑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();
    

    谢谢大家:)

3 个答案:

答案 0 :(得分:3)

您在每次迭代时重新分配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();

这应该与你正在寻找的东西更加一致。

答案 1 :(得分:1)

循环中的代码将最终结果分配给results,这也是搜索的数据。因此,如果Co值是searchTerms中的第二项,则可能无法找到它,因为它会在第一次迭代时被清除。

答案 2 :(得分:1)

每次迭代都会重新分配“结果”,因此结果将只是数组中最后一个搜索项的结果。您还错过了“包含”方法的结束语。在我的头脑中,我会说你可能不得不做类似的事情:

  1. 使用不同的列表变量来保存结果(例如“finalResults”)并仅查询原始列表。

  2. 添加到构建列表:finalResults.AddRange((linq query).ToList());

  3. 使用distinct子句过滤最终结果以清除欺骗