【问题标题】:ViewBag detecting last item MVCViewBag 检测最后一项 MVC
【发布时间】:2016-03-23 20:44:50
【问题描述】:

我有 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();

【问题讨论】:

  • 你在 ViewBag.List 中显示的代码是什么。
  • 那个ViewBag.List是什么类型的? List, Array....

标签: c# asp.net-mvc razor


【解决方案1】:

如果 ViewBag.List 实现 IEnumerable<T> 你可以使用 Last() 你需要castViewBag 中的列表才能访问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 */ 
        } 
    }
}

【讨论】:

  • ViewBag 没有 Count() 或 Last() 之类的函数,我已经尝试过了 :)
  • 当然 ViewBag 没有那个方法,但是存储在 viewbag 中的 List 是一个 IEnumerable,并且有。可能你需要做一个演员表。我进行编辑。
  • 我用不同的方法更新答案,并使用 viewbag 列表的投射。它应该可以工作,如果没有,请告诉我。
  • 谢谢,现在这适用于强制转换,唯一的问题是,该项目不等于 last_item,所以我可以将其更新为 item[0] == last_item[0]。真的很有帮助的答案! :)
  • 哦!抱歉,我认为您在评论中发表的内容只是一个示例。试试这个:var lastFiltered = (ViewBag.List as IEnumerable&lt;int []&gt;).Where(m =&gt; m[0] &lt; 2015).Last();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多