How to use Contains without depending on uppercase and minuscule [duplicate]

3

Follow 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();

It only works like this: João Paulo , if that's the case joão Paulo with the smallest j, it does not work anymore.

Any solution?

    
asked by anonymous 16.03.2017 / 03:18

2 answers

1

There are two other alternatives:

1 - Use 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 - Use regex :

result = result.Where(l => Regex.IsMatch(l.Example, search, RegexOptions.IgnoreCase)).ToList();
    
16.03.2017 / 04:22
1

I believe the most elegant way to solve this is by using an extension 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;
        }
}
    
16.03.2017 / 03:54