Thomas Andreè Wang
Thomas Andreè Wang

Reputation: 3429

How to reverse a LINQ to SQL query

I want to reverse the output of a LINQ to SQL query. and .Reverse() does not work, just crashes the page.

protected void Page_Load(object sender, EventArgs e)
{
    NewsDataContext db = new NewsDataContext();
    var News = from news in db.News                   
               select new 
               {
                   ID = news.NewsID,
                   kort = news.Short
               };

    foreach (var newa in News)
    {
        Panel1.
        Controls.
        Add(new LiteralControl(newa.kort + 
                               "</br>" + 
                               "<a href=Full.aspx?id=" + 
                               newa.ID + 
                               ">Read The full Article</a>"));
    }
}

Is there another way to reverse it?

Upvotes: 4

Views: 6082

Answers (3)

DaveShaw
DaveShaw

Reputation: 52798

If it's news you are trying to show, why not use an OrderBy (or OrderByDescending) to get the items in the order you want rather than the reverse order of the clustered index in the database.

I cannot think of any case where I would need to use Reverse in Linq to Sql.

Example (sorry if the Syntax if off, I prefer Lamda's):

var News = 
     (from news in db.News   
     orderby news.Date descending                 
     select new 
         {
               ID = news.NewsID,
               kort = news.Short
         });

Upvotes: 14

StriplingWarrior
StriplingWarrior

Reputation: 156624

The question is: What are you reversing?

The SQL store doesn't define a specific order on the News table, so simply "reversing" the results of a query without any defined ordering doesn't make sense.

How about something like this?

var News = from news in db.News    
           order by news.PostedTime descending               
           select new 
           {
               ID = news.NewsID,
               kort = news.Short
           };

Upvotes: 5

Adam Rackis
Adam Rackis

Reputation: 83366

I'm guessing SQL Server doesn't know how to translate Reverse into a T-SQL command, so you're getting an exception. You'll probably need to pull the results of the query down from the database, then reverse it.

var News = (from news in db.News                   
               select new 
               {
               ID = news.NewsID,
               kort = news.Short
               }).AsEnumerable().Reverse();

Upvotes: 7

Related Questions