4

I want to enable this function in Linq to Entities (so the filtering happens on the SQL Server)?

public static bool ContainsAny(this string source, StringComparison comparison,
                               IEnumerable<string> searchTerms)
{
  return searchTerms.Any(searchTerm => source.Contains(searchTerm, comparison));
}

My goal is search a table and limit the result by filtering a certain column with the above function, i.e. GetContacts().Where(c => c.FullName.ContainAny(searchTerm)).

4

2 に答える 2

6

First, it's tricky (if possible which I don't know) to use StringComprison in Expressions and expect Linq 2 Entities to translate it to correct Sql statements.

Second, it's tricky to use a custom function like your ContainsAny in an Expression too.

So if I were you, the simple solution is:

GetContacts().Where(c => searchTerms.Any(term => c.FullName.Contains(term)))

which should work in EF4.

于 2012-05-20T19:14:16.290 に答える
0

Take a look at a nuget package I have created

http://www.nuget.org/packages/NinjaNye.SearchExtensions

This will enable the following (and more) which will return results where the search term appears in property specified

var result = GetContacts().Search("searchTerm", c => c.FullName);

For searching multiple terms you can do the following:

var result = GetContacts().Search(searchTerms, c => c.FullName);

The above will return results where any search term appears in the property

This builds up an expression tree which performs the search on the database not in memory, so only matching results are returned form the server.

For more information take a look at the projects GitHub page or my blog posts

于 2014-02-26T10:21:34.073 に答える