Reputation: 800
I am trying to make a suitable linq query to accomodate my search functionality.
I have a table with the following columns: 'firstname' | 'lastname' | 'description'. with the following data: 'Peter' | 'Mulder' | 'This is a little description.'
My 'search' keyword could be something like: "peter" or "a little description".
Now if I use the following linq expression in lambda:
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?
Upvotes: 10
Views: 38343
Reputation: 1
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);
}
}
Upvotes: 0
Reputation: 39085
I think you just have it backwards:
mycontext.persons
.Where(t =>
t.Firstname.Contains(search) ||
t.Lastname.Contains(search) ||
t.Description.Contains(search))
.ToList();
Upvotes: 28
Reputation: 32258
One possible (but probably not the most optimized solution) would be to append all of your fields together and do a Contains
on the search term., e.g.
var result = persons.Where(q => (q.Description + " " q.FirstName + " " q.LastName)
.ToLower()
.Contains(searchTerm.ToLower()))
.ToList();
Upvotes: 4