How to initialize var when it is used for different things in a method

I have a method in my controller that is performing some logic based on data submitted and my varitem should be assigned to different results?

For example my controller's method is something like this:

public ActionResult Index(SearchCriteria criteria)
{
    var db = new EbuyDataEntities();

    //criteria.SearchKeyword = "movie";
    if (!string.IsNullOrEmpty(criteria.SearchKeyword))
    {
       var auctionData = db.Auctions.First(q => q.Description.Contains(criteria.SearchKeyword));
    }
    else
    {
        var auctionData = db.Auctions.OrderBy(item => item.EndTime);
    }

    switch (criteria.GetSortByField())
    {
        case SearchCriteria.SearchFieldType.Price:
            auctionData = auctionData.OrderBy(q => q.CurrentPrice.Value);
            break;
        case SearchCriteria.SearchFieldType.RemainingTime:
            auctionData = auctionData.OrderBy(q => q.EndTime);
            break;
        case SearchCriteria.SearchFieldType.Keyword:
        default:
            auctionData = auctionData.OrderBy(q => q.Title);
            break;
    }

    auctionData = SomeMethod();
    var viewModel = new SearchViewModel();

    return View("Search",viewModel);
}

What is the right way to do something like this.

Jon Skeet
people
quotationmark

Well, two options:

  • Move the declaration to before the if statement, and give it an explicit type:

    IQueryable<Auction> auctionData;
    if (...)
    {
        ...
    }
    else
    {
        ...
    }
    
  • Change the structure to only have a single declaration, e.g. using the conditional operator:

    var auctionData = !string.IsNullOrEmpty(criteria.SearchKeyword)
        ? db.Auctions.Where(q => q.Description.Contains(criteria.SearchKeyword))
        : db.Auctions.OrderBy(item => item.EndTime);
    

Note that I've changed First to Where here - otherwise you would only be matching a single entry, which doesn't sound like much of a search to me, and would make of the rest of the method very odd.

That in itself suggests a third option:

var auctionData = db.Auctions.OrderBy(item => item.EndTime);
var keyword = criteria.SearchKeyword;
if (!string.IsNullOrEmpty(keyword))
{
    auctionData = auctionData.Where((q => q.Description.Contains(keyword));
}

people

See more on this question at Stackoverflow