bob
bob

Reputation: 611

Link for Linq - Even the right google question would be ok

I have a common problem for which an explanation would probably be too lengthy. A good link for the information I need would be greatly appreciated. I have googled but am not completely sure what I am looking for.

I have to search a database on the results of a form. The user has about 20 options to select from, about 10 of which are text fields. I want to provide them the ability to use a wildcard * character at the beginning and end of the text. Further, if there are multiple terms I will interpret the space as a ||.

While writing a method for a single property is simple, generalizing it to many is difficult. What I would like to do is create a private method which would look something like

func<string, bool> getClause(string val, Type property) { }

So if a user searches for someone with a FirstName of bob and a LastName of smith, I'd like to get each part of the query with

qry = qry.Where(
    getClause(FirstName, typeof(People.First)) &&
    getClause(LastName, typeof(People.Last)) && 
    ... );

I hope this is clear. Thanks!

Upvotes: 1

Views: 106

Answers (3)

mousio
mousio

Reputation: 10337

You can dynamically build expression predicates or dynamically build expression trees, there is even a thing called dynamic linq which I have also used. It looks like dynamic searching using linq tries to resolve a similar problem as yours…

Upvotes: 1

Albireo
Albireo

Reputation: 11095

It's not exactly what you asked for, since performs an equality check and not a like, but it might point you into the right direction:

List<String> names = this.namesField.Text.Split(new Char[]() { ' ' }).ToList<String>();
List<String> surnames = this.surnamesField.Text.Split(new Char[]() { ' ' }).ToList<String>();

var query = from a in db.Persons
            where names.Contains(a.Name) && surnames.Contains(a.Surname)
            select a;

There should be a method similar to List<T>.Contains() which performs a partial match

Disclaimer: I have no access to Visual Studio right now so I'm writing this code by memory, typos may be included!

Upvotes: 0

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234644

The PredicateBuilder lets you assemble predicates to use in dynamic queries.

Upvotes: 4

Related Questions