0

I'm using C# Version 6, I having a string variable and I'm trying to sort the LINQ to SQL database table, earlier its working fine but now its not giving appropriate sorting result.

using (var db = new DBEntity()) {
    var propertyInfo = nameof(Client.ClientName);
    var iQuery = db.Clients.OrderByDescending(i => propertyInfo);
    foreach (var item in iQuery.ToList()) {
        Console.WriteLine(item.ClientName);
    }
}

Note: I refereed lots of tutorial in Stack overflow blog and other sites but I can't able to find.

Kindly assist me, whats wrong in my code.

Table Structure and Data

ClientName   ClientStatus
______________________________
Emma         Active
Harry        Active

In both Ascending and Descending I'm getting the same output

ClientName   ClientStatus
______________________________
Emma         Active
Harry        Active

1 Answers1

2

You cannot just pass name (string) of the property which you want to use for sorting. You should use property selector expression:

var iQuery = db.Clients.OrderByDescending(c => c.ClientName);

Expalanation:

LINQ to SQL generates SQL query from expressions which you are passing to query operators. E.g. for ordering you should pass a property selector expression:

OrderByDescending(x => x.SomeProperty)

LINQ to SQL will use this expression to get database field which is mapped to given property (remember, you can change mapping). And generates something like

ORDER BY SomeProperty DESC

But when you are passing string as

OrderByDescending(x => "SomeProperty")

The best think LINQ can do is to sort by string literal which you are passing:

ORDER BY N'SomeProperty' DESC

Of course such kind of 'sorting' will not change order of query result

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459