使用 linq 的 C# 搜索查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16242885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# search query with linq
提问by codingjoe
I am trying to make a suitable linq query to accomodate my search functionality.
我正在尝试进行合适的 linq 查询以适应我的搜索功能。
I have a table with the following columns: 'firstname' | 'lastname' | 'description'. with the following data: 'Peter' | 'Mulder' | 'This is a little description.'
我有一个包含以下列的表:'firstname' | '姓氏' | '描述'。具有以下数据: 'Peter' | '穆德' | “这是一个小小的描述。”
My 'search' keyword could be something like: "peter" or "a little description".
我的“搜索”关键字可能类似于:“peter”或“a little description”。
Now if I use the following linq expression in lambda:
现在,如果我在 lambda 中使用以下 linq 表达式:
mycontext.persons
.Where(t =>
search.Contains(t.Firstname) ||
search.Contains(t.Lastname) ||
search.Contains(t.Description).Select(p => p)
.ToList();
Now I get my result, when I use 'peter', but if I use 'pete' or 'a little description' I get no results. How can I make my linq expression, so it can search through the column data for matches?
现在我得到了我的结果,当我使用 'peter' 时,但是如果我使用 'pete' 或 'a little description' 我没有得到任何结果。如何制作我的 linq 表达式,以便它可以在列数据中搜索匹配项?
采纳答案by Eren Ers?nmez
I think you just have it backwards:
我认为你只是倒退了:
mycontext.persons
.Where(t =>
t.Firstname.Contains(search) ||
t.Lastname.Contains(search) ||
t.Description.Contains(search))
.ToList();
回答by George Johnston
One possible (but probably not the most optimized solution) would be to append all of your fields together and do a Containson the search term., e.g.
一种可能的(但可能不是最优化的解决方案)是将所有字段附加在一起并Contains在搜索词上执行。,例如
var result = persons.Where(q => (q.Description + " " q.FirstName + " " q.LastName)
.ToLower()
.Contains(searchTerm.ToLower()))
.ToList();
回答by testing
try This Code.
试试这个代码。
private void SearchData()
{
Model1Container model = new Model1Container();
try
{
var query = model.Scholars.AsQueryable();
if (!string.IsNullOrEmpty(this.txtSearch.Text))
{
// query = query.Where(x=>x.ScholarName.StartsWith(txtSearch.Text));
query = (from Schl in model.Scholars
where Schl.ScholarName.StartsWith(txtSearch.Text) ||
Schl.PhoneRes.StartsWith(txtSearch.Text) ||
Schl.PhoneOff.StartsWith(txtSearch.Text) ||
Schl.Mobile.StartsWith(txtSearch.Text) ||
Schl.Email.StartsWith(txtSearch.Text)
orderby Schl.ScholarName
select Schl);
}
this.dgvScholarList.DataSource = query.ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
回答by MovGP0
Take a look at NinjaNye.SearchExtensions. It might be exactly what you need.
看看NinjaNye.SearchExtensions。它可能正是您所需要的。

