LINQ corresponding to SQL with clause LIKE 'XXX%'

Asked

Viewed 660 times

7

I am using the following LINQ to return a query:

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

But if the name is Maria, he brings:

José Maria
Maria José

How to bring organized as if running the SQL query? So:

WHERE nome LIKE 'MARIA%'
  • See if this solution helps you: https://answall.com/a/482282/213393

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 the Contains() is even less flexible. If you want to do box insensitivity, or comparison 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;
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

8

You can use Endswith (only names that end with Maria) or Startswith (starting with Maria).

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

Example/Test: https://dotnetfiddle.net/V6y4kv

0

It is also possible to 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

Browser other questions tagged

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