Home > Enterprise >  Retrieve single element from LINQ query
Retrieve single element from LINQ query

Time:12-03

Working with LINQ for the first time in a while and trying to clean something up. I have the following statements:

var element = await _Entities.References
    .Where(db => db.LoadId == request.LoadId && db.ReferenceCode == "123")
    .OrderByDescending(rec => rec.Created).FirstOrDefaultAsync(cancellationToken);

    if (element != null) {
       dto.ElementValue = element.Value;
    }

I'd like to condense this into a single statement if possible but I was having trouble getting just the value from the await method.

CodePudding user response:

You could do something like this:

dto.ElementValue = (await _Entity.References
    .Where(db => db.LoadId == request.LoadId && db.ReferenceCode == "123")
    .OrderByDescending(rec => rec.Created)
    .FirstOrDefaultAsync(cancellationToken))?.Value 
    ?? dto.ElementValue;

Note that technically this changes the behaviour of the code. Previously, if the query doesn't return a result, the ElementValue property is not touched. With a one-liner, if the query doesn't return a result, the ElementValue getter and setter will both be called.

Also, if the query returns a result whose Value is null, the ElementValue property will be set to itself rather than null.

  • Related