比较 C# 中从 ToArray() 方法返回的字符串值
本文关键字:返回 字符串 方法 中从 ToArray 比较 | 更新日期: 2023-09-27 18:34:18
以下是我编写的代码,用于在广告表中按名称搜索特定项目。
public ActionResult SearchResult(string name)
{
var advertisement = db.Advertisements.ToArray(); // retrieve data from database
foreach (var ad in advertisement)
{
if (ad.Title.Equals(name))
{
return View(ad);
}
}
return View(advertisement);
}
即使我搜索数据库中已有的项目,在所有情况下,if 条件都不为真。每次我在视图页面中获取整个项目列表作为结果时。这里有什么问题?
我的广告模型如下所示。
using System;
using System.Drawing; // Image type is in this namespace
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Bartering.Models
{
public class Advertisement
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
public Guid OwnerID { get; set; }
[Required]
public string Category { get; set; }
public byte[] Image { get; set; }
[Required]
[StringLength(200)]
public string Description { get; set; }
}
}
我认为你应该做这样的事情
public ActionResult SearchResult(string name)
{
var ad=db.Advertisements.Where(s=>s.Title.ToUpper()==name.ToUpper())
.FirstOrDefault();
if(ad!=null)
return View(ad);
//Nothing found for search for the name, Let's return the "NotFound" view
return View("NotFound");
}
此代码将获取与我们的检查(标题==名称)匹配的第一个项目(如果存在)并返回它。 如果没有找到与条件匹配的内容, 它将返回一个名为"Notfound"的视图