我开始建立一个网页来优化一些搜索结果。下面的代码运行良好,如果我添加一个查询字符串(即?beds=4,它会返回正确的结果。但是,如果我指定两个查询字符串(即?beds=4&sleeps=8,它返回匹配任何一个的结果(所有有 4 张床的属性(无论睡眠)和所有有 8 张睡眠的属性(无论床),而不是两者。我需要某种 AND 语句,以便结果匹配床和睡眠?
@{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Search";
string searchText = Request.Unvalidated["searchText"];
var searchTerms = searchText.Split('"').Select((element, index) => index % 2 == 0 ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) : new string[] { element }).SelectMany(element => element).ToList();
for (int i=0; i<searchTerms.Count; i++)
{
if (searchTerms[i].ToUpper() == "THE" || searchTerms[i].ToUpper() == "AND" || searchTerms[i].ToUpper() == "AS" || searchTerms[i].ToUpper() == "AN" || searchTerms[i].ToUpper() == "BUT" || searchTerms[i].ToUpper() == "OR" || searchTerms[i].ToUpper() == "OF" || searchTerms[i].ToUpper() == "IF" || searchTerms[i].ToUpper() == "IS" || searchTerms[i].ToUpper() == "IN" || searchTerms[i].ToUpper() == "IT" || searchTerms[i].ToUpper() == "BY" || searchTerms[i].ToUpper() == "TO" || searchTerms[i].ToUpper() == "FOR" || searchTerms[i].Length <= 1 || String.IsNullOrWhiteSpace(searchTerms[i]))
{
searchTerms.RemoveAt(i);
i--; //decrements 'i' if an element is removed because all indexes after this one will drop by one. This ensures that no indexes get skipped.
}
}
var db = Database.Open("StayInFlorida");
string searchQueryString = "";
int termCount = searchTerms.Count;
string[] searchTermsArray = searchTerms.ToArray();
searchQueryString = "SELECT * FROM PropertyInfo WHERE numBedrooms = ";
for (int i=0; i<termCount; i++)
{
if (i != 0)
{
searchQueryString += "OR numBedrooms = "; //Ensures that this is not appended for the first term. Alternatively, of course, you can use "AND", depending on how you want the results returned, but you probably want "OR".
}
searchQueryString += "@" + i + " ";
}
searchQueryString += "UNION ";
searchQueryString += "SELECT * FROM PropertyInfo WHERE numSleeps = ";
for (int i=0; i<termCount; i++)
{
if (i != 0)
{
searchQueryString += "OR numSleeps = ";
}
searchQueryString += "@" + i + " ";
}
searchQueryString += "UNION ";
searchQueryString += "SELECT * FROM PropertyInfo WHERE numBathrooms = ";
for (int i=0; i<termCount; i++)
{
if (i != 0)
{
searchQueryString += "OR numBathrooms = ";
}
searchQueryString += "@" + i + " ";
}
searchQueryString += "ORDER BY anyTermYouWishToOrderBy DESC";
if (searchTermsArray.Length > 0) //Prevents a server-side error if the searchTerm list was empty when converted to the searchTermsArray
{
var queryResults = db.Query(searchQueryString, searchTermsArray);
}
}