【问题标题】:How to check the last index of a for loop, if it possible?如果可能,如何检查 for 循环的最后一个索引?
【发布时间】:2017-05-08 06:53:55
【问题描述】:

希望这是一个简单的问题,我尝试自己做我想做的事情。但我无法解决剩下的部分。

对于每一行,我想检查日期是否高于或低于最后一个。但是怎么做呢?

正如您在图片和示例代码中看到的那样。

Click and see the image exsample

还有如下代码:

@using Scoutpocket.Models.Database;
@model Tuple<List<Properties>, List<SubProperties>, List<Rating>>

<div class="container">

    @foreach (var item in Model.Item1)
    {
        <br />
        <br />
        <b>
            @item.PropertiesName
        </b>

        <br />




        foreach (var item2 in item.SubProperties)
        {
            @item2.SubPropertiesName<br />

            int count = 2;
            int getLast = 1;


            foreach (var item3 in item2.rating.Where(x => x.PlayerID == 1).Take(count).OrderByDescending(x => x.Date))
            {

                for (int i = 0; i < getLast; i++)
                {
                    // Check the index of the last row, and check if the current date is lower or heighter.


                    <b>Compare date on last and newst</b>
                }

                <span>Rating ID: @item3.RatingID</span>
                <span> | </span>
                <span>Value: @item3.Value</span>
                <span> | </span>
                <span>ScoutID: @item3.ScoutID</span>

                <span> | </span>
                <span>PlayerID: @item3.PlayerID</span>

                <span> | </span>
                <span>Date: @item3.Date</span>
                <br/>
            }

        }
    }

</div>

【问题讨论】:

    标签: loops for-loop razor model-view-controller


    【解决方案1】:

    如果您使用List 类型,您可以轻松使用Count 获取大小并使用list.Count - 1 获取最后一个索引。这将返回最后一个元素;确保验证计数,否则可能会引发超出范围的其他明智索引。 例如,

    var _dateHigh = Model.Item1.Last(); // extension methods
    // same for dateLow
    @foreach (var item in Model.Item1) {
        // run the code here.
    }
    

    如果最后一个元素随着每次迭代而改变,那么我建议在循环中使用嵌套变量。我们无能为力,因为您没有共享模型结构,因此我们可以提供的帮助非常少。

    How can I find the last element in a List<> ?

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2018-06-05
      • 2021-05-03
      • 2022-11-22
      • 2021-08-24
      相关资源
      最近更新 更多