Repetitive code for a projected field in a lambda I have a simple projection in my code. Taking away the majority of the fields which are not of interest, it looks like the following:

var result = employments.Select(x =&gt; new EmpListItem
        {
            EndDate = x.EmpRelationship.OrderByDescending(y =&gt; y.EndTime).FirstOrDefault().CancelledBeforeTime ? 
                        x.EmpRelationship.OrderByDescending(y =&gt; y.EndTime).FirstOrDefault().CancelEndTime : 
                        x.EmpRelationship.OrderByDescending(y =&gt; y.EndTime).FirstOrDefault().EndTime,
            JobType = x.JobType
        });


I really dislike how I use x.EmpRelationship.OrderByDescending(y =&gt; y.EndTime).FirstOrDefault() three times. It looks ugly and readability is poor.

Is there a way to use this only once while staying inline? By inline I mean that I don't want to write any code outside of the projection.
You can extract out that repeat call to a variable inside your Select.

var result = employments.Select(x =&gt; 
{
    var empRelationship = x.EmpRelationship.OrderByDescending(y =&gt; y.EndTime).FirstOrDefault();

    return new EmpListItem
    {
        EndDate = empRelationship.CancelledBeforeTime ? 
                      empRelationship.CancelEndTime : 
                      empRelationship.EndTime,
        JobType = x.JobType
    };
});


This will also speed up execution.

The trick behind this is remembering you can execute more than just one statement inside a lambda by using { and }