开发者

Case Statements in LINQ query - AnonymousType to String?

I basically have the following:

public ActionResult Search(string searchString, string clientNo, int status = -1)
{
    v开发者_如何学运维ar statusLst = new List<string>();
    var statusNoQry = from b in db.Briefs
                      orderby b.Status
                      select new  
                      {
                          status = (
                            b.Status == 0 ? "Requested" :
                            b.Status == 1 ? "In Progress" :
                            "Undefined"
                            )
                      };
    statusLst.AddRange(statusNoQry.Distinct()); <<--- ERROR HERE
    ViewBag.status = new SelectList(statusLst);

    var ClientNoLst = new List<string>();
    var ClientNoQry = from b in db.Briefs
                      orderby b.Client_No_
                      where b.Client_Type == 0 
                      select b.Client_No_;
    ClientNoLst.AddRange(ClientNoQry.Distinct());
    ViewBag.clientNo = new SelectList(ClientNoLst);

    var briefs = from b in db.Briefs
                 select b;

    Session["searchString"] = searchString;
    Session["clientNo"] = clientNo;
    if (!String.IsNullOrEmpty(searchString))
    {
        briefs = briefs.Where(s => s.Client_No_.Contains(searchString) || s.Name.Contains(searchString));
    }

    if ((status > -1) && (status < 10))
    {
        briefs = briefs.Where(y => y.Status == status);
    }

    if (string.IsNullOrEmpty(clientNo))
        return View(briefs);
    else
        return View(briefs.Where(x => x.Client_No_ == clientNo));
}

However, I receive the following area:

Error   7   Argument 1: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<string>'

Status is of type int but I would like to cast it to string for my dropdownlist. I'm quite new to all this, what is the appropriate way of achieving this?


Your selector is returning an anonymous type:

select new  
{
    status = (
    b.Status == 0 ? "Requested" :
    b.Status == 1 ? "In Progress" :
    "Undefined"
    )
};

You need to return a set of strings though. The error is telling you exactly what the problem is.

select 
    (b.Status == 0 ? "Requested" :
    b.Status == 1 ? "In Progress" :
    "Undefined");

Edit - You didn't post the rest of the method, but from you have your also not disposing your context object, which can cause problems. Normally you wrap this in a using clause.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜