简体   繁体   中英

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. 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. if there is nothing found which matches the condition, It will return a View called "Notfound"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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