Search code examples
c#case-insensitive

How to make a case insensitive list search in C#?


I've been trying to make a list search method where I could present the items in the list unaffected and after a week going through every search method I could find I realizes that I'm stuck.

The list (posts) stores arrays if that makes any change, this is the search function I got this far that have worked the best but it's case sensitive,

    string searchKey; 
    Console.WriteLine("\nEnter key: ");
    searchKey = Console.ReadLine(); 

    foreach (string result in posts.Where(logg => logg.Contains(searchKey))) 
    {
        Console.WriteLine("\n{0}", result);
    }

Does so I hope that someone know about some great method that I've missed even if I start to think that I'm screwed and should go for some other system instead.


Solution

  • You could use IndexOf with a case-insensitive comparison:

    var query = posts.Where(
        logg => logg.IndexOf(searchKey, StringComparison.CurrentCultureIgnoreCase) != -1);
    foreach (string result in query) 
    {
        Console.WriteLine("\n{0}", result);
    }
    

    Note that while I'd expect this to work for IEnumerable<T>, I suspect that many IQueryable<T> providers (e.g. EF) may well not support this operation.