简体   繁体   中英

Search query using LINQ

I am new to LINQ and I'm trying to search for a result by the event name or event date in ASP.NET MVC Application.

Below is my code:

public ActionResult search(string name, string date)
{
    Database1Entities db = new Database1Entities();

    List<Event> e = db.Events.Where(x => x.EventName.Contains(name) || x.Date.Contains(date)).ToList();

    return View(e);
}

My search.cshtml file basically has two input fields for event name (this is the first field) and event date (second field), and a submit button.

When I search with a part of certain event date, it returns correct result. However, it returns random results that do not contain the particular search string.

I also tried the following code:

List<Event> e = db.Events.Where(x => x.EventName == name || x.Date == date).ToList(); 

In this case also, events with the search string returned no result. Can someone help me figure out how I can make this search work?

When I search with a part of certain event date, it returns correct result. However, it returns random results that do not contain the particular search string.

So you want the result to match the date AND the search string? Then you should use the AND operator (&& instead of ||) like this:

List<Event> e = db.Events.Where(x => x.EventName.Contains(name) && x.Date.Contains(date)).ToList();

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