c# - How to dereference a string that might be null in LINQ -


let's need compare object other objects stored in table called indexes in db. need compare object's x property, string, might null.

i have trim comparedobject's x property before comparing. tried 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 though comparedobjects.x null still throws null reference exception comparedobject.x.trim() expression.

i assume happens due linq conversion?

is there prettier way trim x property without having assign comparedobject.x empty string in case it's null before query ?

edit: i'd elaborate - query reduced simplicity here, comparing 6 other properties. i'd keep in 1 query , not separate 2 queries differ in x property alone. trimming outside query current solution, hoping in-statement solution in case there :)

thanks!

and though comparedobjects.x null still throws null reference exception comparedobject.x.trim() expression.

you better null check before linq statement

if(comparedobject !=null && !string.isnullorempty(comparedobject.x)) {     // code goes here  } 

below code

(ci.x == null || ci.x == string.empty) && (comparedobject.x == null || comparedobject.x == string.empty) 

can change

string.isnullorempty(ci.x) && string.isnullorempty(comparedobject.x) 

and change code 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(); 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -