asp.net mvc - Linq Max with null object and property -


i have flights object list.in list every flight object has segment object list.every item in segment object list has faredisplayinfos object list.every faredisplayinfos object has property such totalfare

i want max totalfare.so coded this.

model.flights.max(a => a.flightsegments.firstordefault().faredisplayinfos.max(c => c.totalfare)); 

but give 0 because totalfare null , value zero. how can eliminate null or 0 object note:not totalfare 0 or null.somet times objects such faredisplayinfos null

edited

with tim-schmelter assistance code set max 0 (zero) although there 43 item in this( leaveroutelistacer) , items has flightsegments segment has many faredisplayinfos , faredisplayinfos has total fare(some fare 0 90....)

 var maxtotalfare = hmodel.leavelist .selectmany(f => f.flightsegments     .where(fs => fs != null && fs.faredisplayinfos != null)     .select(fs => fs.faredisplayinfos.max(fdi => fdi.totalfare))     .defaultifempty(0)) .max(); 

this should work, presuming totalfare nullable:

var maxtotalfare = model.flights     .selectmany(f => f.flightsegments         .where(fs => fs != null && fs.faredisplayinfos != null)         .select(fs => fs.faredisplayinfos.max(fdi => fdi.totalfare ?? 0))         .defaultifempty(0))     .max(); 

Comments