简体   繁体   English

比较从c#中的ToArray()方法返回的字符串值

[英]comparing a string value returned from ToArray() method in c#

Following is a code written by me for searching a specific item by name in the Advertisement table. 以下是我编写的代码,用于通过广告表中的名称搜索特定项目。

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);
}

Even though I search an item which is already in the database, in all cases the if condition is not being true.Each time I get the whole list of items as the result in the view page. 即使我搜索数据库中已经存在的项目,在所有情况下,if条件都不成立。每次,我都会在视图页面中获得整个项目列表。 what is the issue here? 这是什么问题?

My model for Advertisement looks like this. 我的广告模型如下所示。

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; }
     }
}

I think you should be doing something like this 我想你应该做这样的事情

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");
}

This code will get the first item(if exists) which matches with our check (Title==name) and return it. 此代码将获取与我们的支票(Title == name)匹配的第一项(如果存在)并返回它。 if there is nothing found which matches the condition, It will return a View called "Notfound" 如果找不到符合条件的内容,它将返回一个名为“ Notfound”的视图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM