I created a generic search extension method for IQueryable that allows you to search for a single property to see if it contains a search query.
http://jnye.co/Posts/6/c%23-generic-search-extension-method-for-iqueryable
Now I want the user to be able to select several properties to search in each, appropriate if the any property contains text.
Code:
The user enters the following code to perform this search:
string searchTerm = "Essex"; context.Clubs.Search(searchTerm, club => club.Name, club => club.County) //Note: If possible I would rather something closer to the following syntax... context.Clubs.Search(club => new[]{ club.Name, club.County}, searchTerm); // ... or, even better, something similar to this... context.Clubs.Search(club => new { club.Name, club.County}, searchTerm);
This will return any golf club with Essex in the name or in the county.
public static IQueryable<TSource> Search<TSource>(this IQueryable<TSource> source, string searchTerm, params Expression<Func<TSource, string>>[] stringProperties) { if (String.IsNullOrEmpty(searchTerm)) { return source; } // The lamda I would like to reproduce: // source.Where(x => x.[property1].Contains(searchTerm) // || x.[property2].Contains(searchTerm) // || x.[property3].Contains(searchTerm)...) //Create expression to represent x.[property1].Contains(searchTerm) var searchTermExpression = Expression.Constant(searchTerm); //Build parameters var parameters = stringProperties.SelectMany(prop => prop.Parameters); Expression orExpression = null; //Build a contains expression for each property foreach (var stringProperty in stringProperties) { var checkContainsExpression = Expression.Call(stringProperty.Body, typeof(string).GetMethod("Contains"), searchTermExpression); if (orExpression == null) { orExpression = checkContainsExpression; } //Build or expression for each property orExpression = Expression.OrElse(orExpression, checkContainsExpression); } var methodCallExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { source.ElementType }, source.Expression, Expression.Lambda<Func<TSource, bool>>(orExpression, parameters)); return source.Provider.CreateQuery<TSource>(methodCallExpression); }
Error

If I change the number of parameters presented in 1:
Expression.Lambda<Func<TSource, bool>>(orExpression, parameters.First()));
I get a new error:

UPDATE
I wrote a post about the work being discussed on this issue . Check it out also on GitHub .