inline assignment on short hand if in linq select

34 Views Asked by At

I have a query where I am taking entity properties and putting them in properties of a DTO. In one property I am grabbing a property from an associated entity and I want three possible results: 1. empty string if there are no results 2. the property value if there is one result 3. one of the property values plus three dots to tell the user there is more information. This is how my query looks currently:

listOfDtos = await ctx.entity1
    .Select(e1 => new thisDto
    {
        property1 = e1.property1,
        property2 = e1.entity2.Where(e2 => !e2.Field1.Equals(string.Empty)).ToList().Count().Equals(0) ? string.Empty :
            e1.entity2.Where(e2 => !e2.Field1.Equals(string.Empty)).ToList().Count().Equals(1) ? 
                e1.entity2.Where(e2 => !e2.Field1.Equals(string.Empty)).Select(e2 => e2.Field1).Single() :
            e1.entity2.Where(e2 => !e2.Field1.Equals(string.Empty)).Select(e2 => e2.Field1).Take(1) + "...",
        property3 = e1.property3
    })
    .ToListAsync();

So my question is, is there a way to just temporarily store the result of

e2.Field1.Equals(string.Empty)).ToList().Count()

inline inside the select statement to then run my shorthand if checks against instead of having to run it twice? Or is there maybe a better and cleaner way to do this?

Thanks.

0

There are 0 best solutions below