C# LINQ order by not working for a SQL table with a primary key

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi All,

I retrieve some data from a SQL table using the following C# statement.
<pre class="prettyprint" style=" List<MyObject> myList = myClass.getList();// get the List of objects from SQL MYTable
[/code]
Here is the schema(or the table creation query) I used to generate the table named MyTable.
CREATE TABLE [dbo].[MyTable](<br/>
<span class="x_x_Apple-tab-span" style="white-space:pre [id] [int] IDENTITY(1,1) NOT NULL,<br/>
<span class="x_x_Apple-tab-span" style="white-space:pre [float] NULL,<br/>
<span class="x_x_Apple-tab-span" style="white-space:pre [J] [float] NULL,<br/>
<span class="x_x_Apple-tab-span" style="white-space:pre <br/>
CONSTRAINT [PK_MyTABLE] PRIMARY KEY CLUSTERED <br/>
(<br/>
<span class="x_x_Apple-tab-span" style="white-space:pre [id] ASC<br/>
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br/>
) ON [PRIMARY]<br/>
<br/>
GO

After getting data from MyTable I want to order the myList in the descending order of I values. So I use the following C# statement.
<pre class="prettyprint" style=" myList .OrderByDescending(i => i.I).ToList();[/code]
BUT, this is NOT executed as I want. Instead it order it in the ascending order of the primary key that is id. Can you please point out the problem and try to fix this.
If I edit the SQL command in the SQL string it works. For example, when I get the list from the SQL table I can use something like and it works.
<pre class="prettyprint" style=" StringBuilder sql = new StringBuilder("SELECT * FROM MyTable ORDER BY I DESC)[/code]
<br/>
If I use a command like myList.Reverse(); it works as well.
But why does not the following LINQ statement work in my scenario?
<pre class="prettyprint" style=" myList .OrderByDescending(i => i.I).ToList();[/code]
I hope you can help me out to understand this and try to fix the problem.
Also, is there any advantage in adding the ToList(); method at the end of the above LINQ statement performance wise?
I thank you so much for your help on this.
Clive
<br/>

View the full article
 
Back
Top