简体   繁体   中英

C# search query with linq

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?

I think you just have it backwards:

mycontext.persons
    .Where(t => 
        t.Firstname.Contains(search) || 
        t.Lastname.Contains(search) || 
        t.Description.Contains(search))
    .ToList();

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., eg

var result = persons.Where(q => (q.Description + " " q.FirstName + " " q.LastName)
                    .ToLower()
                    .Contains(searchTerm.ToLower()))
                    .ToList();

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);
    }
}

Take a look at NinjaNye.SearchExtensions . It might be exactly what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM