【问题标题】:Index out of range exception while iterating through list c#遍历列表c#时索引超出范围异常
【发布时间】:2015-08-29 17:40:45
【问题描述】:

这是我的控制器代码:

    public ActionResult Index(string priceMin, string priceMax)
    {
        lstEventType = HttpRuntime.Cache["EventType"] as List<string>;
        if (lstEventType == null || !lstEventType.Any())
        {
            lstEventType = new List<string>();
            lst = artistModel.fillDropDown();
            lstEventType = lst.Where(p => p.lookupType == "EventType").Select(q => q.lookupValue).ToList();
            HttpRuntime.Cache["EventType"] = lstEventType;
        }
        ViewData["EventType"] = lstEventType;
        artistList = artistModel.displayArtist();    
        if (!String.IsNullOrEmpty(priceMin))
        {
            aSession.priceMin = priceMin;
            ViewData["priceMin"] = priceMin;
            artistList = artistList.Where(p => (string.IsNullOrEmpty(p.strHiddenCost) ? 0 : Convert.ToInt32(p.strHiddenCost)) >= Convert.ToInt32(priceMin)).ToList();
        }
        if (!String.IsNullOrEmpty(priceMax))
        {
            aSession.priceMax = priceMax;
            ViewData["priceMax"] = priceMax;
            artistList = artistList.Where(p => (string.IsNullOrEmpty(p.strHiddenCost) ? 0 : Convert.ToInt32(p.strHiddenCost)) <= Convert.ToInt32(priceMax)).ToList();
        }         
        return View(artistList);
    }

如果这个艺术家列表返回非值,那么我没有收到任何错误。但是,如果艺术家列表返回 null,则视图中的以下代码部分将引发异常。我无法弄清楚这个艺术家列表如何影响 viewdata["EventType"]。

下面是我的代码

@{
   List<string> EventTypes = ViewData["EventType"] as List<string>;
        foreach (string eventType in EventTypes)
          {    
            <li><a> <span class="pull-right"></span>@eventType</a></li>
          }
   }

在遍历此循环时,我遇到了索引超出范围异常。如果我的控制器向该视图返回一个非空列表,那么它工作正常。但是如果控制器返回空列表来查看这个迭代失败。

【问题讨论】:

  • 也许您的 ViewData 中没有“EventType”条目
  • 我在 viewdata 中得到 3 行。
  • 您显示的代码中没有任何内容可以解决该错误。调试你的代码!而且您的 html 无效(li 元素不能是 em 元素的子元素)
  • 这个 em 只是为了这个 stackoverflow 。
     标签实际上并没有出现在我的代码中。

标签: c# list asp.net-mvc-4 foreach controller


【解决方案1】:

变量命名很重要,尝试使用 EventTypeList 而不是 EventTypes。 此外,由于您使用的是 foreach,因此您应该使用 nullcheck。

@{
    List<string> EventTypeList= ViewData["EventType"] as List<string>;
    if (EventTypeList != null && EventTypeList.Count > 0){
        foreach (string eventType in EventTypeList)
        {
            <li><a> <span class="pull-right">@eventType</span></a></li>
        }
    }
}

添加的 nullcheck 将解决控制器发送空列表时发生的问题。

【讨论】:

  • 对我来说,这个 EventTypeList 永远不会为空。所以没有放任何空检查。控制器正在向我的强类型视图返回另一个列表。
  • 我已经更新了答案,如果您返回的是一个空列表而不是一个空列表,请同时进行 .Count 检查。
  • "如果控制器返回空列表以查看" .Count 检查将解决该问题。还有什么问题?
  • 我已经用我的修改运行了你的代码,不能破坏它。它工作正常。您的问题的解决方案是 nullcheck 和 Count。如果还有其他问题,那么我没有看到它。祝你好运。
  • 当artistList为空的时候你有没有尝试过任何条件?
猜你喜欢
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
相关资源
最近更新 更多