繁体   English   中英

使用LINQ select进行类型推断失败

[英]Type inference failure with LINQ select

我在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子句或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) })

我不知道确定我的电话出了什么问题

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

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)
                 });

一旦开始将查询表达式语法与“ from”一起使用,则还必须使用“ select”而不是.Select()。

您可以使用“ let”完成您想要的操作(计算一次TimeSpan,然后使用两次)

  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)
                 });

);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM