加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何创建一个空的SelectList

发布时间:2020-12-15 18:30:53 所属栏目:百科 来源:网络整理
导读:我有folloiwng动作方法: public JsonResult LoadSitesByCustomerName(string customername){ var customerlist = repository.GetSDOrg(customername) .OrderBy(a = a.NAME) .ToList(); var CustomerData; CustomerData = customerlist.Select(m = new Selec
我有folloiwng动作方法:
public JsonResult LoadSitesByCustomerName(string customername)
{
    var customerlist = repository.GetSDOrg(customername)
                                 .OrderBy(a => a.NAME)
                                 .ToList();
    var CustomerData;
    CustomerData = customerlist.Select(m => new SelectListItem()
    {
        Text = m.NAME,Value = m.NAME.ToString(),});
    return Json(CustomerData,JsonRequestBehavior.AllowGet);
}

但目前我在var CustomerData上遇到以下错误;:

implicitly typed local variables must be initialized

所以我不知道如何创建一个空的SelectList来将其分配给var变量?
谢谢

解决方法

你可以尝试这个:
IEnumerable<SelectListItem> customerList = new List<SelectListItem>();

你得到的错误是合理的,因为

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

另一方面,您可以尝试以下方法:

var customerList = customerlist.Select(m => new SelectListItem()
                   {
                       Text = m.NAME,});

第二个赋值将起作用的原因是,编译器可以通过这种方式推断变量的类型,因为它知道LINQ查询的类型返回.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读