I have a Sitecore 6.6 solution running MVC and Razor. I am have the following line;
@Html.Raw(Sitecore.Context.Database.GetItem(myList.Children.LastOrDefault()["myField1"]).Fields["myField2"])
The above works fine, except the order it sorts in. I need to get the latest item based on the __Created field. LastOrDefault seems to take the last item in the tree, which does not always correspond to the actual latest created item.
Can it be done in one line as the above?
How about this:
myList.GetChildren()
.OrderBy(x => x[Sitecore.FieldIDs.Created])
.Reverse()
.LastOrDefault()
I guess this would work too:
myList.GetChildren()
.OrderBy(x => x.Statistics.Created)
.Reverse()
.LastOrDefault()
Keep in mind though that first all the children will be retrieved and then the sorting will happen. If you have a lot of children it will be slow.
One general note, you shouldn't do this in the View really. You're putting too much logic in there. Your model should provide the item that you need (last created).