I am working with an open-source system and have been given the requirement to sort a set of entities by relevance to a term.
The set needs be ordered with exact matches first, then the "startswith" matches, then the "contains" matches.
The lambda expression I came up with to achieve this is:
var results = products.OrderBy(p => p.Name.StartsWith(searchTerm) ? Convert.ToString((char)0) : p.Name);
At present, the pre-written system works such that it invokes an OrderBy method with an instance of a lambda expression with reflection, in order to sort the results.
To minimise the amount of time spent on this task, I would like to conform to this convention. I've tried to create an instance of a lambda expression and pass it in as a parameter to MethodInfo.Invoke() but because it's got a variable in it, it throws an exception.
The code for the sort method of this system is:
private IOrderedQueryable<ReferenceProduct> OrderProducts(IQueryable<ReferenceProduct> filteredProducts, String sortExpression, String sortDirection, out String checkedSortExpression, out String checkedSortedDescending)
{
ProductListManager.SortExpression correspondingSortExpression = this.SortExpressions.OrderByDescending(se => String.Equals(se.Code, sortExpression, StringComparison.OrdinalIgnoreCase))
.DefaultIfEmpty(new SortExpression<Guid> { Code = String.Empty, Expression = rp => rp.ProductId })
.FirstOrDefault();
checkedSortExpression = correspondingSortExpression.Code;
checkedSortedDescending = String.Equals("desc", sortDirection, StringComparison.OrdinalIgnoreCase) ? "desc" : "asc";
MethodInfo orderMethod = (checkedSortedDescending.Equals("desc", StringComparison.OrdinalIgnoreCase) ? (Queryable.OrderByDescending) : new Func<IQueryable<Object>, Expression<Func<Object, Object>>, IOrderedQueryable<Object>>(Queryable.OrderBy)).Method.GetGenericMethodDefinition().MakeGenericMethod(typeof(ReferenceProduct), correspondingSortExpression.Expression.ReturnType);
IOrderedQueryable<ReferenceProduct> orderedProducts = orderMethod.Invoke(null, new Object[] { filteredProducts, correspondingSortExpression.Expression }) as IOrderedQueryable<ReferenceProduct>;
return orderedProducts;
}
Has anyone got any ideas?
Thanks in advance.
Ryan