Hi I have a linq query where I compare an object with all other entity stored in my database. Firstname and lastname are mandatory fields so I don’t have to check for null. But in the case of street I have to do these checks.
I want to match if both fields are null or empty strings or that they are the same. The below linq query is working fine.
But I was wandering isn’t there any way to make it more readable. For example with a custom function like Bool FieldsAreEqualOrBothNullOrEmpty(r.street, request.street)
Can’t figure how to do that and if it’s possible.
var same =
from r in db.Requests
where r.firstName.ToLower() == request.firstName.ToLower()
&& r.lastName.ToLower() == request.lastName.ToLower()
//Seems long to just compare two fields
&& ( string.IsNullOrEmpty(r.street) && string.IsNullOrEmpty(request.street) )
|| r.street.ToLower() == request.street.ToLower()
select r;
return same;
I would simplify:
The nice thing about the this is that it keeps the query simple in each case.
You could use similar logic for the first two if you choose, and it could also be moved to an expression-based utility method. Untested:
then: