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?
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));
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With