Code Performance Question: Get & Convert two DateTime to strings

I need to get the OrderDtl NeedBy and ShipBy dates, not a hard thing and I’ve done it plenty of times but in this case I need both and wondering which is more efficient code; two DB calls direct to the field or one DB call to pull both and then convert to string or is my two examples total trash and there is a better way?

Option 1:

lineSBD = Convert.ToDateTime( Db.OrderDtl.Where( r => r.Company == Session.CompanyID && r.OrderNum == OrderNum && r.OrderLine == oLine).Select( r => r.RequestDate ).Min() ).ToString("MM/dd/yyyy");

lineNBD = Convert.ToDateTime( Db.OrderDtl.Where( r => r.Company == Session.CompanyID && r.OrderNum == OrderNum && r.OrderLine == oLine).Select( r => r.NeedByDate ).Min() ).ToString("MM/dd/yyyy");    

Option 2:

var lineDates = (from r in Db.OrderDtl where r.Company == Session.CompanyID && r.OrderNum == OrderNum && r.OrderLine == oLine select new {oRow.NeedByDate, oRow.RequestDate}).FirstOrDefault();   

lineNBD = string.Format("{0:MM/dd/yyyy}", lineDates.NeedByDate); 
lineSBD = string.Format("{0:MM/dd/yyyy}", lineDates.RequestDate);  

Option 2 is better ,Option 1 is querying the DB twice is like doing two select statements in sql vs just 1

Further more option 1 you don’t need to convert to DateTime they are already DateTime, so you can remove the ConvertToDateTime portion.
Also in option one why are you doing .Min? you can do FirstOrDefault() since you’ll only ever get 1 result from the query

2 Likes

That was copy/paste from another BPM where they wanted to MIN date forgot to edit it. :flushed:

1 Like