当它是在一个方法中使用不同的事情如何初始化变种 [英] How to initialize var when it is used for different things in a method

查看:64
本文介绍了当它是在一个方法中使用不同的事情如何初始化变种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的控制器是基于提交和我的 VAR 项目应该被分配到不同的结果?数据执行一些逻辑的方法

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.

推荐答案

好吧,有两个选项:


  • 如果语句之前移动声明,并给它一个明确的类型:

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

    这篇关于当它是在一个方法中使用不同的事情如何初始化变种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆