简体   繁体   中英

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!

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();

may be you can try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM