I have a list of a very simply entity, which has a nullable DateTime property.
e.g.
class MyEntity
{
int Id{ get;set; }
string Category { get; set; }
DateTime? Date{ get; set ; }
}
var myentities = new List<MyEntity>(..);
I’d like to return the First() item in the list where either the date is the “oldest”, or most in the past, or closest to DateTime.Min, whatever way you want to word it, or if there are no dates set, then get the first item.
This can be done with two statements:
var myEntity = myentities
.Where(me => me.Date != null)
.OrderBy(me => me.Date)
.FirstOrDefault();
if (myEntity == null)
myEntity = myentities.First();
But is there a way to do this in a single statement?
Try this
Or you can just fold your collection