搜索匿名模型的项目



我有:

   IEnumerable<CustomModel> model = //some joins and select here;

我该怎么做这样的事?

   if(!String.IsNullOrEmpty(keyword))
        {
            return View(model.Where(m => m.Description.Contains(keyword) ||
                m.Title.Contains(keyword)).ToList());
        }
   return View(model.ToList());

如果你想知道的话,这个代码不起作用。我想做的是只返回包含搜索关键字的项目。错误如下:

   Object reference not set to an instance of an object. 
   Description: An unhandled exception occurred during the execution of the current web request.            
   Please review the stack trace for more information about the error and where it originated in     
   the code. 
   Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
 Line 132:            if(!String.IsNullOrEmpty(search_idea))
 Line 133:            {
 Line 134:                return View(model.Where(m => m.Description.Contains(search_idea) ||
 Line 135:                    m.Title.Contains(search_idea)).ToList());
 Line 136:            }

提前谢谢。

我看到这段代码有两个问题。

首先,考虑一下keyword可能是区分大小写的,您应该在不考虑区分大小写情况的情况下更改代码进行搜索。

if(!String.IsNullOrEmpty(keyword))
{
    return View(model.Where(m => 
        m.Description.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1 ||
        m.Title.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1)
    .ToList());
}
return View(model.ToList());

其次,确保m.Descriptionm.Title不为空,因为调用null.IndexOfnull.Contains将导致NullReferenceException:

if(!String.IsNullOrEmpty(keyword))
{
    return View(model.Where(m => 
        (m.Description ?? "").IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1 ||
        (m.Title ?? "").IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1)
    .ToList());
}
return View(model.ToList());

最新更新