2

Assume a DbSet<Thing> things; and Thing has a Name property.

If I want to retrieve a list of things that match a list of names, it's pretty straightforward:

var names = new List<string>{"John", "Jacob", "Jinkelheimer", "Smith"};

return things.Where(t => names.Contains(t.name));

However, what if I want to match a list of partial name possibilities?

var nameBits = (new List<string>{"ohn", "mit"}).ToLower();

// this doesn't seem good / right / efficient
things.Where(t => nameBits
   .Select(bit => EF.Functions.Like(t.Name, $"%{bit}%")
   .Any(m => m)
);

// I could also go with:

things.Where(t => nameBits
     .Select(bit => t.Name.Contains(bit)).Any(m => m)
);

... but I don't know how efficient any of those will be. How would I write the linq query that would efficiently match "John", "Johnathan", "Smith", "Smitty", etc using ohn and mit?

Scott Baker
  • 10,013
  • 17
  • 56
  • 102

1 Answers1

1

The great thing about Entity Framework is that you can always drop to raw SQL when things aren't working out on the C# front.

var names = context.Names
    .FromSqlRaw("select Name from Names where name like %{0}%", name)
    .ToList();

Writing Raw SQL Queries in Entity Framework Core

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501