I\'m trying to build some code for dynamically sorting a Linq IQueryable<>.
The obvious way is here, which sorts a list using a string for the field name
http
The easiest way to do this would be to have your AddSort() function take an Expression
static void Main(string[] args)
{
var query = from m in Movies select m;
var sorter = new Sorter();
sorter.AddSort("NAME", m => m.Name);
}
class Sorter
{
public void AddSort(string name, Expression> func)
{
string fieldName = (func.Body as MemberExpression).Member.Name;
}
}
In this case, i've used object as the return type of the func, because its easily automatically convertible, but you could implement that with different types, or generics, as appropriate, if you require more functionality. In this case, since the Expression is just there to be inspected, it doesn't really matter.
The other possible way is to still take a Func, and store that in the dictionary itself. Then, when it comes to sorting, and you need to get the value to sort on, you can call something like:
// assuming a dictionary of fields to sort for, called m_fields
m_fields[fieldName](currentItem)