如何从包含非前缀关键字的列表中进行搜索

时间:2010-04-10 22:19:04

标签: c# search autosuggest

我正在编程一个程序来搜索列表中的名称,即使关键字不在名称前面我也需要找到它们(这就是我的意思是非前缀)

例如如果我的列表是乐器,我在搜索文本框中键入“guit”
它应该找到名称​​“吉他,Guitarrón,原声吉他,低音吉他......”
或类似Longdo Dictionary's搜索建议。

这是我的简单和愚蠢的算法(这就是我所能做的)

    const int SEARCHROWLIMIT = 30;
    private string[] DoSearch(string Input, string[] ListToSearch)
    {
        List<string> FoundNames = new List<string>();

        int max = 0;
        bool over = false;
        for (int k = 0; !over; k++)
        {
            foreach (string item in ListToSearch)
            {
                max = (max > item.Length) ? max : item.Length;
                if (k > item.Length) continue;
                if (k >= max) { over = true; break; }
                if (!Input.Equals("Search")
                    && item.Substring(k, item.Length - k).StartsWith(Input, StringComparison.OrdinalIgnoreCase))
                {
                    bool exist = false;
                    int i = 0;
                    while (!exist && i < FoundNames.Count)
                    {
                        if (item.Equals(FoundNames[i]))
                        {
                            exist = true;
                            break;
                        }
                        i++;
                    }
                    if (!exist && FoundNames.Count < SEARCHROWLIMIT)
                        FoundNames.Add(item);
                    else if (FoundNames.Count >= SEARCHROWLIMIT) over = true;
                }
            }
        }
        return FoundNames.ToArray();
    }

我认为这个算法对于大量名称来说太慢了,经过几次试错,我决定添加SEARCHROWLIMIT来打破操作 而且我也认为有一些现成的方法可以做到这一点。

另一个问题是我需要按类别字符串,打击乐器...... 以及原籍国搜索乐器。所以我需要按类型和国家搜索它们。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:6)

使用LINQ,您可以编写如下代码:

var resultSet = products

    // filter products by category
    .Where(product => product.Category == "strings")

    // filter products by origin
    .Where(product => product.Origin == "italy")

    // filter products whose name contains a word starting with "guit"
    .Where(product => (" " + product.Name).Contains(" guit"))

    // limit the result set to the first 30 matching products
    .Take(30);

如果您的产品组合相当小,则可以使用LINQ-to-Objects。否则,您应该使用数据库并查看LINQ-to-SQL。

答案 1 :(得分:2)

一个字。数据库!

说真的,如果您想要进行所有这些不同的搜索,请考虑将数据放入数据库中,并使用可简化您所遇到的分类问题的模式。 Sql Server Express现在支持full text search,这对于您尝试执行的搜索类型非常有用。

关于在Linq-to-Sql中使用FTS,有一篇不错的博文here

答案 2 :(得分:0)

static List<string> GetItemsWithWordsStartingWithSubstring(List<string> list, string substring)
{
    var query = from str in list
                from item in str.Split(' ')
                where item.StartsWith(substring, StringComparison.InvariantCultureIgnoreCase)
                select str;

    return query.ToList();
}

我希望我已经正确地阅读了你的intiial问题。此函数将返回列表中包含以子字符串开头的单词的任何项目。可以向拆分参数添加更多标点符号。给出一个包含以下内容的列表:

  

“abcdef”,“defabc”,“def abc”,“xyz”

搜索“abc”会找到“abcdef”和“def abc”,但不能找到“defabc”。