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; }
}
I want to create a property LastActivitythat returns the last action date. This is easy enough for a collection Pictures:
public DateTime LastActivity
{
get { return Pictures.Max(x => x.LastUpdated); }
}
However, I also want to consider a property LastUpdatedin an object Album. 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 he will do the conversion Max()twice. Is there a better way to write this code?
Answer
This is the solution I came across 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;
}
}
You should ensure that if you do Max()in an empty collection, you will get an exception, so you need to check if there is anything in the collection in the first place.