I faced this situation today and could not find on the web what I wanted.
Look at this code,
myCollection.Select(g => new ReportLine
{
cds = (sectors.FirstOrDefault(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE)) != null ?
sectors.FirstOrDefault(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE)).USER != null?
sectors.FirstOrDefault(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE)).USER.USER_FIRSTNAME : "": "")
+ " " +
(sectors.FirstOrDefault(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE)) != null ?
sectors.Where(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE)).FirstOrDefault().USER != null?
sectors.Where(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE)).FirstOrDefault().USER.LASTNAME : "" : "")
});
Basically "myCollection" is a list of a deep class and this request goes into it extract a first and last name and put them in an other class while checking if there is no null values.
You noticed to achieve that I checked the same thing 6 times:
sectors.FirstOrDefault(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE))
(probably painful for performance)
Does a way exists to "store" the value within the linq expression ? something like this:
myCollection.Select(g => new ReportLine
{
cds = ((var tmp =sectors.FirstOrDefault(s => s.SECT_CODE.Equals(g.Contract.Station.Sector.SECT_CODE))) != null ?
tmp.USER != null?
tmp.USER.USER_FIRSTNAME + "" + tmp.USER.LASTNAME: "": "")
});