ViewBag检测最后一项MVC

时间:2015-09-28 07:12:23

标签: c# asp.net-mvc razor

我有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 */ 
        } 
    }
}

编辑:我将那里存储了数年作为匿名对象

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

ViewBag.List = GetYears();

1 个答案:

答案 0 :(得分:4)

如果ViewBag.List实施IEnumerable<T>,您可以使用Last() 您需要cast ViewBag中的列表才能访问IEnumerable的方法或按索引访问,我认为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 */ 
        } 
    }
}