Lambda query to change the order of the list by date
I have this function that shows a list of posts 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 is a way to change the order in the lambda request without calling the callback method? Or are you calling Reverse () the only way to do it?
+2
source to share
2 answers
You just want to use the extension method OrderByDescending
, not OrderBy
.
Indeed, this would be a more efficient method, since it only requires one iteration of the collection, not two.
messages.AddRange(Messages.OrderByDescending(message => message.DateAdded));
+6
source to share
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();
}
+3
source to share