i have dateSend Column and dateEdit Column in product table, i can select max dateSend with this code:
(from pro in Products.ToList() select new { pro.DateSend }).Max(); but i have max between dateSend and dateEdit, please help me.
(from pro in Products.ToList() let max = Max(pro.DateSend, pro.DateEdit) select max).Max() static DateTime? Max(DateTime? a, DateTime? b) { if (!a.HasValue && !b.HasValue) return a; // doesn't matter if (!a.HasValue) return b; if (!b.HasValue) return a; return a.Value > b.Value ? a : b; } If you're not opposed to ditching the query syntax it's simpler to do:
DateTime max = Products.Max(p=>p.DateSend > p.DateEdit ? p.DateSend : p.DateEdit); ((from pro in Products.ToList() select pro.DateSend).Union( from pro2 in Products.ToList() select pro.DateEdit )).Max(); Same code but with One LinQ
(From pro in Products.ToList Let max = {pro.DateSend, pro.DateEdit}.Max select max).Max If pro items not a valid DateTime, It will crash or return unexpected result.
Other solution(Parsing the Products list items):
(From pro in Products.ToList Let DSend as DateTime = Convert.ToDateTime(Iif(ValidDateTime(pro.DateSend), pro.DateSend, DateTime.MinValue)) Let DEdit as DateTime = Convert.ToDateTime(Iif(ValidDateTime(pro.DateEdit), pro.DateEdit, DateTime.MinValue)) Let MaxDate as DateTime= {DSend, DEdit}.Max select MaxDate).Max private function ValidDateTime(ByVal Dat as Object) as Boolean if Dat Is Nothing OrElse IsDbNull(Dat) OrElse String.IsNullOrEmpty(Dat) then return false end if return true end function You can replace the ValidDateTime with an "Iif".
Other example returning max value of Double items, but in the personalized object(MyObject), items are String type.
(From Item as MyObject in MyListOfObject Let Frec as Double = Convert.ToDouble(Iif(String.IsNullOrEmpty(Item.Frecuency),0,Item.Frecuency)) Let Pot as Double = Convert.ToDouble(Iif(String.IsNullOrEmpty(Item.Power),0,Item.Power)) Let max as Double= {Frec, Pot}.Max select max).Max Recap
I hope this code helps to someone. Sorry for my English.
DateTime?... Is that correct?