Reputation: 1412
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?
Upvotes: 2
Views: 1307
Reputation: 532435
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();
}
Upvotes: 3
Reputation: 147280
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));
Upvotes: 6