Let’s say I have an entity that looks like this:
public class Album()
{
public DateTime LastUpdated { get; set; }
public List<Picture> Pictures { get; set; }
}
What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:
public DateTime LastActivity
{
get { return Pictures.Max(x => x.LastUpdated); }
}
However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:
public DateTime LastActivity
{
get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
? Pictures.Max(x => x.LastUpdated)
: this.LastUpdated) };
}
But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?
Answer
This is the solution I came up with, based on the accepted answer:
public virtual DateTime LastActivity
{
get
{
var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
return max > this.LastUpdated ? max : this.LastUpdated;
}
}
The thing to watch out for is that if you do a Max() on an empty collection, you’ll get an exception, so you have to check to see if there’s anything in the collection first.
Just store the max in a variable rather that performing the calculation twice.