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

前端之家收集整理的这篇文章主要介绍了c# – 如何创建一个空的SelectList前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有folloiwng动作方法
  1. public JsonResult LoadSitesByCustomerName(string customername)
  2. {
  3. var customerlist = repository.GetSDOrg(customername)
  4. .OrderBy(a => a.NAME)
  5. .ToList();
  6. var CustomerData;
  7. CustomerData = customerlist.Select(m => new SelectListItem()
  8. {
  9. Text = m.NAME,Value = m.NAME.ToString(),});
  10. return Json(CustomerData,JsonRequestBehavior.AllowGet);
  11. }

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

  1. implicitly typed local variables must be initialized

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

解决方法

你可以尝试这个:
  1. 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.

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

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

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

猜你在找的C#相关文章