PriceCheaperton
PriceCheaperton

Reputation: 5349

Adding FirstOrDefault to my query?

How do i add first or default to my controller:

public ActionResult Index(string searchString)
{
    var customers = from s in db.TicketDetails
                    select s;

    if (!String.IsNullOrEmpty(searchString))
    {
        //search criteria
        customers = customers.Where(s => s.SupportRef.Contains(searchString));
    }
    return View(db.TicketDetails.ToList());
}

I need to make sure my results only return 1 record. If they return null then I need to pass in dummy values.

Upvotes: 0

Views: 347

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

Make sure how many items you have returning from the query.

  • If more than 2 return your default value.
  • If nun return your default value.
  • If the item returned is null return your default value.
  • Otherwise you have one valid item in your collection and you return it:

All together you can write it this way:

public ActionResult Index(string searchString)
{
    var defaultReturnValue = //you default dummy object

    if(String.IsNullOrEmpty(searchString))
        return View(defaultReturnValue);

    var customers = (from s in db.TicketDetails
                     where s.SupportRef.Contains(searchingString)
                     select s).Take(2).ToList(); // execute query here so not to execute it twice

    return View(customers.Count > 1 ? defaultReturnValue :
                                      customers.FirstOrDefault() ?? defaultReturnValue);
}

I've added the Take(2) so the generated query will take up to 2 records and so, in a case that there is more than a single record it will still not bring all of them

Upvotes: 2

Related Questions