Search code examples
c#linqcase-sensitive

LINQ To SQL Contains Case Sensitive Searching


When I use below query, it gets result perfectly. But it is case-sensitive. Here is my codes:

    IQueryable<article> results;
    if (rrbAuthor.IsChecked)
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid where a.author.Contains(textBox1.Text) select a).Distinct();
    else if (rrbKeywords.IsChecked)
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid where k.word.Contains(textBox1.Text) select a).Distinct();
    else
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid where a.title.Contains(textBox1.Text) select a).Distinct();

    ListArticles(results, 1);

How can I manage to get results in in-sensitive case?


Solution

  • You can transform string into lower case, using ToLower() method and then do comparison
    You can also use null propagation in oder to avoid NullReference Exception in case some of the stirngs is null.

    Try following

      IQueryable<article> results;
      if (rrbAuthor.IsChecked)
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
                   where a.author?.ToLower().Contains(textBox1.Text?.ToLower()) == true
                   select a).Distinct();
      else if (rrbKeywords.IsChecked)
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
                   where k.word?.ToLower().Contains(textBox1.Text?.ToLower()) == true
                   select a).Distinct();
      else
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
                   where a.title?.ToLower().Contains(textBox1.Text?.ToLower()) == true
                   select a).Distinct();
      ListArticles(results, 1);