How to use Contains without capitalization and minuscule

Asked

Viewed 70 times

3

Follows the code:

var result= db.Table.Where(l => l.Field== value).ToList();

var search = "jOãO pAuLo";
result = result.Where(l => l.Example.Contains(search)).ToList();

Only works that way: João Paulo, if so joão Paulo with letter j minusculo, no longer works.

Some solution ?

2 answers

1

I believe the most elegant way to solve this, eh using an Xtension Method.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var list = new List<String>();
        list.Add("AAAAAO");
        list.Add("BBB");

        list = list.Where(x=> x.Contains("bbb", StringComparison.OrdinalIgnoreCase)).ToList();

        Console.WriteLine(list.Count().ToString());

    }

}

public static class Extensions
{
    public static bool Contains(this string str, string strComparacao, StringComparison argumento)
        {
            return str.IndexOf(strComparacao, argumento) >= 0;
        }
}
  • It’s another alternative tbm, this one works.

1


There are two other alternatives:

1 - Using ToLower or ToUpper:

result = result.Where(l => l.Example.ToLower().Contains(search.ToLower())).ToList();

result = result.Where(l => l.Example.ToUpper().Contains(search.ToUpper())).ToList();

2 - Utilzar regex:

result = result.Where(l => Regex.IsMatch(l.Example, search, RegexOptions.IgnoreCase)).ToList();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.