Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order LINQ by "string" name

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.

like image 884
Skinner Avatar asked Dec 16 '10 20:12

Skinner


People also ask

How to order by string in c#?

Firstly, set a string array. string[] values = { "tim", "amit", "tom", "jack", "saurav"}; Use the Sort() method to sort.

How do I sort a list in ascending order LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

How does OrderBy work in LINQ?

In the LINQ-OrderBy method, it supports both query and method syntax. Let's see the query syntax with examples. OrderBy sorts the values of a collection in ascending or descending order. It sorts the collection in ascending order by default because ascending keyword is optional here.

How OrderBy works c#?

In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.


1 Answers

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);
like image 172
Andrei Andrushkevich Avatar answered Oct 14 '22 04:10

Andrei Andrushkevich