Home:ALL Converter>Linq To Sql Search Multiple Columns and Multiple Words

Linq To Sql Search Multiple Columns and Multiple Words

Ask Time:2009-05-22T21:10:06         Author:KClough

Json Formatter

I am trying to do an autocomplete search using a webservice and Linq To Sql to access the database.

Here is my code. This returns results that match any of the search terms, I would like to modify this so each result contains all of the search terms.

I'm aware that SQL full text search is probably the most elegant solution, but I'd like to see if this functionality is possible without modifying the database.

 string[] searchTerms = searchString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToArray();
        IQueryable<AccountResult> results = db.cdAccounts
            .Select(x =>
                new AccountResult()
                {
                    idAccount = x.id_Account,
                    AccountName = x.AccountNme,
                    AccountNumber = x.AccountNum
                }).Distinct().OrderBy(x => x.AccountName);
        foreach (string searchTerm in searchTerms)
            results = results.Where(x => x.AccountName.Contains(searchTerm) || x.AccountNumber.Contains(searchTerm));

        return results.OrderBy(x => x.AccountName).Take(40).ToList();

Author:KClough,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/897750/linq-to-sql-search-multiple-columns-and-multiple-words
KClough :

I ended up doing using linq to search for the fist term, then if there were multiple terms. I'm open to improvements/optimizations.\n\n//...\nif (searchTerms.Count() > 1)\n{\n List<string> remainingSearchTerms = new List<string>();\n for (int x = 1; x < searchTerms.Count(); x++)\n remainingSearchTerms.Add(searchTerms[x]);\n List<SearchResult> matchingResults = new List<SearchResult>();\n\n foreach (SearchResult result in allResults)\n if (MatchSearchTerms(new string[] { result.Name, result.Number, result.id.ToString() }, remainingSearchTerms.ToArray()))\n matchingResults.Add(result);\n\n return matchingResults.OrderBy(x => x.Name).Take(MaxResults).ToList();\n}\nelse\n return allResults.OrderBy(x => x.Name).Take(MaxResults).ToList();\n//...\n\nprivate bool MatchSearchTerms(string[] searchFields, string[] searchTerms)\n{\n bool match = true;\n foreach (string searchTerm in searchTerms)\n {\n if (match)\n {\n bool fieldMatch = false;\n foreach (string field in searchFields)\n {\n if (field.ToLower().Contains(searchTerm.ToLower()))\n {\n fieldMatch = true; //Only one field needs to match the term\n break;\n }\n }\n match = fieldMatch;\n }\n else\n break;\n }\n return match;\n}\n",
2009-06-16T17:25:58
yy