【问题标题】:Why am I getting "Cannot convert lambda expression to type 'string' because it is not a delegate type"?为什么我会收到“无法将 lambda 表达式转换为类型‘字符串’,因为它不是委托类型”?
【发布时间】:2011-08-03 22:50:14
【问题描述】:

我有一个名为 LookupTable 的简单表,其中包含两个字段:Id (int) 和 Description (nvarchar),我想用它们来填充下拉列表。

以下代码给了我错误:

IEnumerable<SelectListItem> items = 
  _entities.LookupTable.Select(t=> new SelectListItem {Value = t.Id, 
                                                       Text = t.Description } );

我有一个正在使用的 System.Linq;已经声明了,如果我尝试 t.Id.ToString() 会出现运行时错误。

我一定错过了一些简单的东西,对吧?

【问题讨论】:

    标签: asp.net-mvc-3 linq-to-entities


    【解决方案1】:

    从您的问题中不清楚_entities.LookupTable 的类型是什么。如果我们假设它是一些IQueryable&lt;SomeModel&gt;IEnumerable&lt;SomeModel&gt;,其中SomeModel 包含两个属性IdDescription,您必须确保正确地将这两个值转换为字符串,如Value 和@987654328 SelectListItem 的 @ 属性是字符串。

    您也可以尝试通过调用.ToString() 来急切地执行查询:

    var items = _entities
        .LookupTable
        .ToList()
        .Select(t => new SelectListItem 
        {
             Value = t.Id.ToString(), // <-- notice that you might need a ToString if the Id property is integer 
             Text = t.Description 
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多