6

PROBLEM SOLVED!!!

The solution is Linq.Dynamic

You do it like this:

(from c in Context.AccountCharts 
    where c.Account_FK == account && c.Year_FK == year select c).OrderBy(order);

You have to download the System.Linq.Dynamic.dll and include it into your project.


Is there a way to order a linq query by the name of a field. like this:

from c in Context.AccountCharts 
    where c.Account_FK == account && c.Year_FK == year 
    orderby c["ColName"] select c;

Or

from c in Context.AccountCharts 
    where c.Account_FK == account && c.Year_FK == year 
    orderby c.GetType().GetField("ColName") select c;

None of these two works but I hope you know of a way to do this.

Skinner
  • 61
  • 3
  • You want to sort the entire table, based a field which can change row-by-row? that is, if ColName is "Account_FK" in the first row, and "Year" is the second row, by which column do you wish to sort it? – James Curran Dec 16 '10 at 20:43
  • So you're trying to use reflection inside a LINQ query? What happens if you go for `orderby c.GetType().GetField("ColName").GetValue(c)`? – Anon. Dec 16 '10 at 20:44
  • @James, @Anon, I think he simply wants the `orderby` to be variable rather than hardcoded. So in one case, he wants to sort on ColumnA, another ColumnB, and would rather not write multiple functions that differ only on the `orderby` line. If so, his use of the term `field` is unfortunate, since that implies a private member variable rather than a column in a database. – Anthony Pegram Dec 16 '10 at 20:46
  • if i use the GetField("ColName") i get: System.InvalidOperationException: Cannot order by type 'System.Reflection.FieldInfo' – Skinner Dec 16 '10 at 20:47
  • @Skinner: Did you include the `GetValue(c)` on the end, or not? – Anon. Dec 16 '10 at 20:49
  • if i use c.GetType().GetField("No").GetValue(c) i get: System.InvalidOperationException: Cannot order by type 'System.Object'. And if i cast it to string that i know ColName is i get: The argument 'value' was the wrong type. Expected 'System.String'. Actual 'System.Object'. – Skinner Dec 16 '10 at 20:53

2 Answers2

1

I spend to many time to resolve this issue, but didn't find any better than:

var queryExpression;
if (c["ColName"]=="CreateDate")
    queryExpression.OrderBy(x => x.CreateDate);
Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42
0

Hope this will work too though not tested

Context.AccountCharts.Where(c=>c.Account_FK == account && c.Year_FK == year).OrderBy(o=>o.order);