ViewBag检测最后一项MVC

本文关键字:一项 MVC 检测 最后 ViewBag | 更新日期: 2023-09-27 18:15:00

我在ViewBag中有对象列表。有没有办法检查那个项目是否是Razor视图中ViewBag中的最后一个?

@if (ViewBag.List != null)
{
    foreach(var item in ViewBag.List)
    {
        if(item[0] == **LAST ITEM** ) // here I want to check if it is the last item in my ViewBag.List
        { 
            /* do stuff */ 
        } 
    }
}

编辑:I存储there年作为一个匿名对象

public object GetYears(){
    return result.Distinct().OrderBy(i => i.startYear).Select(c => new[]
                {
                    c.startYear
                });
}
ViewBag.List = GetYears();

ViewBag检测最后一项MVC

如果ViewBag.List实现了IEnumerable<T>,则可以使用Last()为了访问IEnumerable的方法或通过索引访问,您需要在ViewBagcast列表,我假设startYearint

@if (ViewBag.List != null)
{
    var last_item = (ViewBag.List as IEnumerable<int[]>).Last();
    foreach(var item in ViewBag.List)
    {
        if(item[0] == last_item[0]) // here I want to check if it is the last item in my ViewBag.List
        { 
            /* do stuff */ 
        } 
    }
}

或者您可以使用传统的方式使用Count并通过index访问元素

@if (ViewBag.List != null)
{
    IEnumerable<int[]> viewbag_list = (ViewBag.List as IEnumerable<int[]>);
    var last_item = viewbag_list[viewbag_list.Count()-1];
    foreach(var item in ViewBag.List)
    {
        if(item[0] == last_item[0]) // here I want to check if it is the last item in my ViewBag.List
        { 
            /* do stuff */ 
        } 
    }
}