在c#中迭代列表时出现索引超出范围异常
本文关键字:索引 范围 异常 迭代 列表 | 更新日期: 2023-09-27 18:10:18
我的控制器代码:
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);
}
如果这个artistList返回非值,那么我没有得到任何错误。但是如果artistList返回null,视图中下面的代码部分就会抛出异常。我无法弄清楚这个artistList是如何影响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>
}
}
当通过这个循环迭代时,我得到了索引超出范围的异常。如果我的控制器返回一个非空列表到这个视图,那么它的工作很好。但是,如果控制器返回空列表来查看,则迭代失败。
变量命名很重要,尝试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将解决控制器发送空列表时发生的问题。