我有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();
答案 0 :(得分:4)
如果ViewBag.List
实施IEnumerable<T>
,您可以使用Last()
您需要cast
ViewBag
中的列表才能访问IEnumerable
的方法或按索引访问,我认为startYear
是int
@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 */
}
}
}