LINQ corresponding to SQL with LIKE clause 'XXX%'

7

I'm using the following LINQ to return a query:

.Where(c => c.Nome.Contains(nome)).OrderBy(c => c.Nome)

But if the name is Maria , it brings:

José Maria
Maria José

How to bring organized as if executing SQL query? So:

WHERE nome LIKE 'MARIA%'
    
asked by anonymous 12.10.2015 / 21:38

3 answers

9

The LIKE can be at the beginning, at the end, or anywhere. So the equivalence is this:

From the documentation we see that Contains() is even less flexible. If you want to do with box insensitivity, or compare according to some specific criteria, you have to write an auxiliary code ( text.IndexOf("Maria", StringComparison.OrdinalIgnoreCase) >= 0 ).

using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main() {     
        var pessoas = new List<Pessoa>() {
            new Pessoa() { Nome = "Maria José" },
            new Pessoa() { Nome= "José Maria"}, 
            new Pessoa() { Nome= "José Maria José"} 
        };
        WriteLine("Início");
        foreach (var pessoa in pessoas.Where(p => p.Nome.StartsWith("Maria")).OrderBy(p => p.Nome)) {
            WriteLine(pessoa.Nome);
        }
        WriteLine();
        WriteLine("Fim");
        foreach (var pessoa in pessoas.Where(p => p.Nome.EndsWith("Maria")).OrderBy(p => p.Nome)) {
            WriteLine(pessoa.Nome);
        }
        WriteLine();
        WriteLine("Qualquer lugar");
        foreach (var pessoa in pessoas.Where(p => p.Nome.Contains("Maria")).OrderBy(p => p.Nome)) {
            WriteLine(pessoa.Nome);
        }
    }
}

public class Pessoa {
    public string Nome;
}

See running on dotNetFiddle .

    
12.10.2015 / 22:17
7

You can use EndsWith (only names that end with Mary) or StartsWith (start with Mary).

var filtrados = usuarios.Where(c => c.Nome.EndsWith("Maria"))
                        .OrderBy(c => c.Nome)
                        .ToList();

Example / Test: link

    
12.10.2015 / 21:51
0

You can also use this way:

Similar to Like%:

SqlMethods.Like(c.Nome, "Maria%")

Similar to% Like:

SqlMethods.Like(c.Nome,"%Maria")

Similar to% like%:

SqlMethods.Like(c.Nome,"%Maria%")

This method uses the library: System.Data.Linq.SqlClient

    
15.03.2016 / 20:24