【问题标题】:How Can I Concat 2 SelectList lists?我如何 Concat 2 选择列表列表?
【发布时间】:2018-10-12 06:58:32
【问题描述】:

我需要将 2 个 SelectList 合并为一个,Concat() 想要一个我无法弄清楚的演员表。

SelectList sl1 = new SelectList(Cust.GetCustListOne(), "Id", "Last", 2);
SelectList sl2 = new SelectList(Cust.GetCustListTwo(), "Id", "Last", 4);
SelectList sl3 = sl2.Concat(sl1);

第 3 行的错误是 CS0266 无法将类型 IEnumerable 隐式转换为 SelectList。存在显式转换(您是否缺少演员表?)

如下铸造

SelectList sl3 = (SelectList)sl2.Concat(sl1);

失败并出现以下错误

InvalidCastException:无法将 <ConcatIterator>d__59-1[System.Web.Mvc.SelectListItem] 类型的对象转换为 System.Web.Mvc.SelectList 类型

我在这里缺少什么演员?

【问题讨论】:

  • 你试过SelectList sl3 = new SelectList(sl2.Concat(sl1));吗?

标签: c# asp.net-mvc


【解决方案1】:

这是因为 System.Linq.Enumerable.Concat 返回 IEnumerable 并且正如错误所暗示的那样,它不能将其隐式转换为它没有转换的东西。

变化:

SelectList sl3 = sl2.Concat(sl1);

到以下,这是可行的,因为 SelectList 构造函数接受IEnumerable

SelectList sl3 = new SelectList(sl2.Concat(sl1));

【讨论】:

  • 最好先得到这两个,然后创建列表,而不是创建两个不使用的列表
  • @Orel 这不起作用,它返回 SelectListItem.Text ='System.Web.Mvc.SelectListItem' 和 SelectListItem.Value = null 的 SelectList。
  • @Camilio 同意,我从现有代码开始,不想再改变,然后变成了....为什么我不能这样做 :>)
【解决方案2】:

在两个 SelectList 上使用 .union

    List<person> persons = new List<person>();
    persons.Add(new person() { id = 1, name = "Abel" });
    persons.Add(new person() { id = 1, name = "Joseph" });

    List<person> persons2 = new List<person>();
    persons2.Add(new person() { id = 1, name = "Stacey" });
    persons2.Add(new person() { id = 1, name = "John" });

    SelectList s1 = new SelectList(persons);
    SelectList s2 = new SelectList(persons2);
    SelectList s3 = new SelectList(s1.Union(s2));

【讨论】:

  • .AddRange 上榜:SelectList s3 = new SelectList(s1.AddRange(s2));
猜你喜欢
  • 2016-03-03
  • 2019-10-08
  • 1970-01-01
  • 2016-07-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
相关资源
最近更新 更多