【问题标题】:Type inference failure with LINQ select使用 LINQ 选择类型推理失败
【发布时间】:2016-04-10 15:14:51
【问题描述】:

我在 MVC 中有一个模板 TimeSpan。

查看

@model TimeSpan?
@{
    var id = "id" + Guid.NewGuid().ToString().Substring(0, 5);
    string format = (string)(this.ViewData["format"] ?? @"hh\:mm\:ss");

    IEnumerable<SelectListItem> listValues;

    if (this.Model.HasValue)
    {
        listValues = from x in Enumerable.Range(0, 96)
                     .Select(x => new TimeSpan(9000000000 * x))
                     .Select(x => new SelectListItem {Selected = true, Value = x.ToString(), 
                                                       Text = x.ToString(format) })
    }
    else
    {
        listValues = from x in Enumerable.Range(0, 96)
                     select new SelectListItem { Value = x.ToString(), 
                                                 Text = x.ToString(format) };   
    }

}
<div class="field-small">
    @Html.DropDownListFor(x => x, listValues, new { id = id})
</div>
<script type="text/javascript"">
    $("#@id")
        .turnAutoComplete();
</script>

但有例外

select 子句中的表达式类型不正确。类型 调用“Select”时推理失败。

查询正文必须以 select 子句或 group 子句结尾

线路错误

listValues = from x in Enumerable.Range(0, 96)
                 .Select(x => new TimeSpan(9000000000 * x))
                 .Select(x => new SelectListItem { Selected = true, Value = x.ToString(),
                                                   Text = x.ToString(format) })

我不知道我的线路出了什么问题

【问题讨论】:

    标签: c# html sql asp.net-mvc-4


    【解决方案1】:

    您尝试将查询表达式语法与常规方法调用混合使用,结果得到的结果不是完整的查询表达式。你可以使用:

    listValues = from x in Enumerable.Range(0, 96)
                 let ts = new TimeSpan(9000000000 * x)
                 select new SelectListItem {
                     Selected = true,
                     Value = ts.ToString(),
                     Text = ts.ToString(format)
                 };
    

    或者只是:

    listValues = Enumerable.Range(0, 96)
                     .Select(x => new TimeSpan(9000000000 * x))
                     .Select(x => new SelectListItem {
                         Selected = true,
                         Value = x.ToString(),
                         Text = x.ToString(format)
                     });
    

    【讨论】:

      【解决方案2】:

      一旦开始使用带有“from”的查询表达式语法,您还必须使用“select”而不是 .Select()。

      你可以用“让”做你想做的事(计算一次时间跨度,然后使用它两次)

        listValues = (from x in Enumerable.Range(0, 96)
                      let ts = new TimeSpan(9000000000 * x)
                      select new SelectListItem 
                      { 
                          Selected = true, 
                          Value = ts.ToString(),
                          Text = ts.ToString(format)
                       });
      

      );

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 2018-08-21
        • 1970-01-01
        • 2020-12-30
        • 1970-01-01
        • 2018-05-15
        • 2016-04-24
        相关资源
        最近更新 更多