簡體   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