gpt4 book ai didi

c# - Linq 搜索不返回所有条目

转载 作者:行者123 更新时间:2023-12-02 08:39:57 25 4
gpt4 key购买 nike

伙计们,我有两个问题...首先我有一个 linq 查询搜索,它查询姓名和姓氏并从数据库返回结果。例如,如果我搜索 John,它会返回完美的 John travolta(我的问题是)如果我搜索 john travolta 的名字和姓氏,它会找不到结果吗?...帮助。

问题二:再次搜索时如何清除搜索结果?因为当我第二次搜索时,上一次搜索的结果是

public class SearchResults
{
public string Name { get; set; }
public string Surname { get; set; }

public SearchResults(string name, string surname)
{
Name = name;
Surname = surname;
}



protected void btnSearch_Click(object sender, EventArgs e)
{
string search = txtSearch.Text.ToLower().TrimEnd();
lsSearchResults = null;
lsSearchResults = new List<SearchResults>();
Repeater1.DataSource = null;
lsSearchResults.Clear();
Repeater1.DataSource = "";
}

if (string.IsNullOrWhiteSpace(txtSearch.Text))
{
lblResults.Text = "Please enter a password & Em@ilAddress";

lsSearchResults.Clear();

return;
}

else
{
var found = (from User in myDB.Memberships
where User.Name.ToLower().Contains(txtSearch.Text.ToLower()) ||
User.Surname.ToLower().Contains(txtSearch.Text.ToLower())
select new { User.Name, User.Surname });

// validates items in search query if Exist
if (!ChillZARdev.App_Code.Utilities.IsEmpty(found))
{
foreach (var user in found)
{
lsSearchResults.Add(new SearchResults(user.Name, user.Surname));
// ls.Add(user.Name + " " + user.Surname);

// Response.Write(user);
}
Repeater1.DataSource = lsSearchResults;

Repeater1.DataBind();

}
}

最佳答案

简短的解决方案是在 where 子句中同时包含名字和姓氏:

var found = (from User in myDB.Memberships
where User.Name.ToLower().Contains(txtSearch.Text.ToLower()) ||
User.Surname.ToLower().Contains(txtSearch.Text.ToLower()) ||
(User.Name + " " + User.Surname).ToLower().Contains(txtSearch.Text.ToLower())

但是,这意味着搜索“Travolta john”不会返回任何结果。

如果这很重要,您应该按空格拆分字符串,然后搜索每个单词。

List<string> searchSplit = txtSearch.Text.ToLower().Split(' ');

var found = (from User in myDB.Memberships
where IsMatch(searchSplit, User)

private bool IsMatch(List<string> searchSplit, User User){
return searchSplit.Count() ==
searchSplit.Where(x => User.Name.ToLower().Contains(x) ||
User.Surname.ToLower().Contains(x)).Count();
}

理想情况下,如 Steve B has commented , 最好实现一个预建的搜索引擎,它需要比简单的自定义搜索更多的搜索工具。但这取决于您的预算/要求。

关于c# - Linq 搜索不返回所有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17526532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com