This is because
OrderByColumn
is just a string. It is unrelated to the values that you are sorting: expression
x => OrderByColumn
returns the same value for all instances of
x
, so it makes sense that the sort does not work.
Making it work is a more interesting question: if you are good at
reflection[
^], you can skip the rest of this answer. If you don't like reflection, you can still do it: replace your sort expression with
query.OrderBy(x => ChooseColumn(x, OrderByColumn))
, and implement
ChooseColumn
as follows:
public object ChooseColumn(string columnName, TabMaster x) {
switch(columnName) {
case "MyColumn1": return x.MyColumn1;
case "MyColumn2": return x.MyColumn2;
case "MyColumn3": return x.MyColumn3;
default: throw new InvalidOperationException("Unknown: "+columnName);
}
}