Saturday, April 21, 2007

ORDER BY 1 Will Not Work In LINQ The Same As In SQL

I installed Visual Studio Orcas Beta 1 last night and now I am playing around with LINQ

You know how you can do the following in SQL

SELECT *
FROM SomeTable
ORDER BY 1

This will order the resultset by the first column. This of course is not good practice but that is not the point here. In LINQ if you do orderby 1 (that is right no space between order and by) it looks like that line is skipped, no error or exception is thrown

Dump the following code in a C# console application and try for yourself
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] names = { "Burke", "Connor", "Frank",
"Everett", "Albert", "George",
"Harris", "David" };

IEnumerable expr = from s in names
where s.Length == 6
orderby 1
//order by s
select s.ToUpper();

foreach (string item in expr)
Console.WriteLine(item);
Console.ReadLine();

}


}
}

2 comments:

zproxy said...

This i believe is by design. yea are sorting by the value 1 which in turn does not sort anything as each item sortable value is 1.

Instead what you should do would look something like this:

var r =
from u in stuff
select u
orderby u.GetType().GetFields()[1].GetValue(u);

Anonymous said...

"order by 1" used the way you describe is just sorting by the first column and assuming that it's an auto-incremented id. The right way would be to simply sort on that column by name.