0

I'm doing a search function in WebAPI but it only returns the item if it's correct accordingly to the XML data. For example, it will only return the item if I write "Milk" or "Apple". How can I make it return these items if I write "milk", "apple" or maybe "aPpLe"?

Controller:

   public IHttpActionResult GetItems(string name)
    {

        List<Item> allItems = GetAllItems();

        return Ok(allItems.Where(i => i.Name.Contains(name)));
    }
Jacob
  • 45
  • 6
  • `allItems.Where(i => i.Name.ToLower().Contains(name.ToLower()))` – Adrian Mar 19 '19 at 09:53
  • 1
    Possible duplicate of [Case insensitive 'Contains(string)'](https://stackoverflow.com/questions/444798/case-insensitive-containsstring) – Selvin Mar 19 '19 at 09:54

2 Answers2

-1

You can convert the strings to lower case.

public IHttpActionResult GetItems(string name)
{
    List<Item> allItems = GetAllItems();

    return Ok(allItems.Where(i => i.Name.ToLower().Contains(name.ToLower())));
}

I did not test it but it should work.

pitaridis
  • 2,801
  • 3
  • 22
  • 41
  • *I did not test it but it should work.* [no, it won't](http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html) – Selvin Mar 19 '19 at 10:55
-1

CODE

 public IHttpActionResult GetItems(string name)
 {
     List<Item> allItems = GetAllItems();

     //We are ignoring the Case Sensitivity and comparing the items with name
     return Ok(allItems.Where(x => x.Name.Equals(name,StringComparison.CurrentCultureIgnoreCase));
}
  • Equals not equals Contains – Selvin Mar 19 '19 at 10:54
  • @Selvin We are comparing the individual item from allItems list using Equals(name,StringComparison.CurrentCultureIgnoreCase) which will internally ignore the case of my name. – Mohit Talreja Mar 19 '19 at 17:31
  • If i have an element which i am iterating in my list and comparing with name (input parameter) i can use equals as compare to contains as it will give me a reliable result. For Ex:- If i have a word Mapple and i use contains for apple keyword in my resulting output i will get a failure as i am looking for apple keyword not Mapple. – Mohit Talreja Mar 20 '19 at 19:56
  • Milk shake, apple pie... For search we rather use contains... Also OP used Contains in his code... – Selvin Mar 20 '19 at 22:54