JN
less than a minute read

Search Extensions: ContainingAll string search feature

#expression-trees#linq#extension-methods#search#csharp#nuget#fluent

ContainingAll() string search feature

Recently I have been working on a couple of new additions to SearchExtensions. One of these changes was a request from a user to have the ability to only return results where all of the search terms were hit against any number of properties.

I'm pleased to say this feature is now part of the NinjaNye.SearchExtensions nuget package.

<p class="nuget-badge"><code>PM> Install-Package NinjaNye.SearchExtensions</code></p>

How to use ContainingAll()

var result = context.Model.Search(x => x.Name, x => x.Desc)
                          .ContainingAll("test", "search");

This will return only records where all the search terms are matched in any of the defined properties, meaning that the following records would all be returned for the above.

{ Name= "test search", Desc = "desc"}
{ Name= "test", Desc = "search"}
{ Name= "ninja", Desc = "searchtest"}

This feature is also implemented as an IQueryable extension method so can perform the search on the data source so that you don't need to bring every potential record into memory before you apply the filter.

IQueryable implementation

The SQL that is generated when using the IQueryable extension method will be similar to the following:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[Desc] AS [Desc]
FROM [dbo].[Test] AS [Extent1]
WHERE (([Extent1].[Name] LIKE N'%test%') OR ([Extent1].[Desc] LIKE N'%test%'))
  AND (([Extent1].[Name] LIKE N'%search%') OR ([Extent1].[Desc] LIKE N'%search%'))

Thanks to @JamesReate for raising this as an issue. Chances are I would not have realised this was a requirement had you not made the request.

If you have a new feature request, please get in touch by adding a comment below, contact me on twitter (@ninjanye) or you can raise an issue on the github project page


Leave a comment