Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dereference a string that might be null in LINQ

Let's say I need to compare an object to other objects stored in a table called Indexes in my DB. I need to compare by the object's X property, which is a string, but it might be null.

I also have to trim my comparedObject's X property before comparing. I tried to do the following:

List<Guid> Ids = DataContext.Indexes.Where(ci =>
                 (comparedObject.X != null && ci.X != null ? 
                 ci.X == comparedObject.X.Trim() :
                 (ci.X == null || ci.X == string.Empty) && (comparedObject.X == null || comparedObject.X == string.Empty))).Select(ci => ci.Id).ToList();

And even though comparedObjects.X is null it still throws a null reference exception for the comparedObject.X.Trim() expression.

I assume that happens due to the linq conversion?

Is there a prettier way to trim the X property without having to assign comparedObject.X an empty string in case it's null before the query ?

EDIT: I'd like to elaborate - this query was reduced for simplicity here, I am also comparing about 6 other properties. I'd like to keep this in 1 query and not separate to 2 queries that differ in the X property alone. Trimming outside the query is my current solution, I was hoping for a in-statement solution in case there is any :)

Thanks!

like image 936
Omri Aharon Avatar asked Nov 15 '25 17:11

Omri Aharon


1 Answers

And even though comparedObjects.X is null it still throws a null reference exception for the comparedObject.X.Trim() expression.

you better do a null check before the linq statement

if(comparedObject !=null && !string.IsNullorEmpty(comparedObject.X))
{
    // your code goes here 
}

below code

(ci.X == null || ci.X == string.Empty) && (comparedObject.X == null || comparedObject.X == string.Empty)

can change to

string.IsNullorEmpty(ci.X) && string.IsNullorEmpty(comparedObject.X)

And i would change code as below

List<Guid> Ids = DataContext.Indexes.Where(ci =>
                 (string.IsNullorEmpty(ci.X) && string.IsNullorEmpty(comparedObject.X)) || ci.X == comparedObject.X.Trim())
                .Select(ci => ci.Id).ToList();
like image 155
Damith Avatar answered Nov 18 '25 05:11

Damith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!