views:

222

answers:

2

I have this function that shows a list of messages in reverse order.

 protected void setupMessages(IList<Message> Messages)
 {
     List<Message> messages = new List<Message>() ;
     messages.AddRange( Messages.OrderBy(message => message.DateAdded).Reverse());
     MessagesRepeater.DataSource = messages;
     MessagesRepeater.DataBind();
 }

I was wondering if there was a way to reverse the order within the lambda query without calling the Reverse Method? Or is calling Reverse() the only way to do this?

+3  A: 

You simply want to use the OrderByDescending extension method, as opposed to OrderBy.

Indeed, this would be a more efficient method, since it only requires one iteration of the collection rather than two.

messages.AddRange(Messages.OrderByDescending(message => message.DateAdded));
Noldorin
+3  A: 

Use OrderByDescending

messages.AddRange( Messages.OrderByDescending( message => message.DateAdded ) );

In fact, you can simplify the whole thing:

protected void setupMessages(IList<Message> Messages)
{     
     MessagesRepeater.DataSource = Messages.OrderByDescending( message => message.DateAdded )
                                           .ToList();
     MessagesRepeater.DataBind();
}
tvanfosson
Thanks, for the answer. You are both right, but Noldorin was first.Thanks for the code, but the reason that I used the intermediate collection was because I got an error saying my data source must implement ICollection or can perform data source paging if AllowPaging is true.
NetHawk
@NetHawk: Easiest just to call `ToList()` at the end, in that case. :)
Noldorin
Updated to include the ToList() call. I wasn't sure if you could bind to the IEnumerable directly or not. I guess now we know.
tvanfosson