SearchExtensions: New search all string properties functionality
A new release of NinjaNye.SearchExtensions is now available from nuget. One of the additions in the latest release is the ability to search all string properties of a given type.
###Search All feature
This is a feature that was requested by a user on a previous post. Effectively, they wanted to perform a search on all string properties of the target type. With a bit of thought, this was fairly easy to implement. I already had a method that could take a list of properties, so all I needed to do was create a list of Expressions
to represent each property of the given type. To do this I created a helper method as follows:
/// <summary>
/// Builds an array of expressions that map to every string property on an object
/// </summary>
/// <typeparam name="T">Type of object to retrieve properties from</typeparam>
/// <returns>An array of expressions for each string property</returns>
public static Expression<Func<T, string>>[] GetStringProperties<T>()
{
var parameter = Expression.Parameter(typeof(T));
var stringProperties = typeof(T).GetProperties()
.Where(property => property.PropertyType == typeof(String)
&& property.CanRead);
var result = new List<Expression<Func<T, string>>>();
// Loop through each string property...
foreach (var property in stringProperties)
{
Expression body = Expression.Property(parameter, property);
// ...and build a lambda expression to represent it
result.Add(Expression.Lambda<Func<T, string>>(body, parameter));
}
return result.ToArray();
}
Once this was complete, I simply created a new Search
overload and used my new helper method to retrieve the properties and pass them on to my existing search system.
/// <summary>
/// Search ALL string properties for a particular search term
/// </summary>
public static IQueryable<T> Search<T>(this IQueryable<T> source, string searchTerm)
{
if (String.IsNullOrEmpty(searchTerm))
{
return source;
}
// Get all string properties from object
var stringProperties = ExpressionHelper.GetStringProperties<T>();
// Continue with search
return source.Search(new[] {searchTerm}, stringProperties);
}
This can now be used to search all string properties on a given object as follows:
var result = data.Search("searchTerm");
I hope you find the new functionality useful.
NinjaNye.SearchExtensions is availabel as a nuget package and can be installed using the following code in your Package Manager Console
<p class="nuget-badge"><code>PM> Install-Package NinjaNye.SearchExtensions</code></p>As always, any comments are greatly appreciated, if it wasn't for a comment on a previous post, the Search All feature would not have been implemented.