views:

511

answers:

2

Hello,

I'm using Linq to sql and Linq Dynamic OrderBy.

I know linq dynamic can do simple sorting like - orderby("column_name").

But does it support something more complex like queries with "CASE WHEN" in them ?

string orderbyQuery = "(CASE WHEN (username == 100) THEN 1 ELSE 0 END) DESC)";

here is my query :

var u = from u in db.users
        orderby(orderbyQuery)
        select u;

the above example doesn't work! , any idea if its possible? any other way to do it?

thanks

+1  A: 
var u = from u in db.users
        orderby u.username == 100 ? 1 : 0 descending
        select u;
Dave
i have to use dynamic query because ,i have a int[] realUsers = 100, 22 , 77 , 12 , etc...i want to sort Users table based on that int[], meaning show the users in "realUsers" first.
dan
You can replace that u.username == 100 ? 1 : 0 with (almost) any logic you want for ordering, you're essentially just writing it in C# instead of Sql. Without knowing exactly how you're trying to order it's hard to give a better example than converting your original code...
Dave
A: 

This is my current code:

int[] onlineUsers = GetOnlineArray(); // Cache stored array in example {100,101,102,...,...,...,N} 

using (var db = new MyDataContext()) 
{  
   var users = (from u in db.Users 
   where u.u_gender == gender  
   orderby (onlineUsers.Contains(u.u_username)) descending 
   select u.u_username).Skip(startRowIndex).Take(maximumRows).ToList(); 
 } 

This works but its limited to 2100 online users (because linq pass each array item as a different paramter and sql is limited to 2100 param per query).

The reason for the question above is that i wanted to change this query to use dynamic linq for the orderby. so i built a function that return a sql OR string based on the int[] onlineUsers.

in example

string orderbyQuery = "100 == u.u_username || 101 == u.u_username || 102 == u.u_username" 

and the new query is :

using (var db = new MyDataContext()) 
    {  
       var users = (from u in db.Users 
       where u.u_gender == gender  
       orderby (orderByQuery) descending 
       select u.u_username).Skip(startRowIndex).Take(maximumRows).ToList(); 
     } 

but the new query doesn't work.

any idea?

dan
You should really edit your original question rather than post an update as an answer. Stack Overflow isn't really built the same as a discussion forum, so adding extra detail as an answer will become confusing when there is more than one answer.
Dave
will do next time...any answer regarding the question?
dan