Meow
Meow

Reputation: 19071

How to assign empty string if the value is null in linq query?

I have following LINQ query to get a set of data.

var fields = from row in datarows
from field in row
from col in columnnames
where field.Key == col
select new { ColumnName = col, FieldValue = field.Value };

The problem is that my code that handle the fields after this query fails because field.Value of some rows are returning null.

My goal is to assign an empty string if null is detected.

Something like if field.Value == null, then field.Value = ""

Is it possible to do so in linq query?

Upvotes: 15

Views: 57883

Answers (7)

mfsumption
mfsumption

Reputation: 353

I also learned that if you are concatenating two fields in a linq field assignment and you are using the null-coalescing operator on only one of the fields, then you need to put parentheses around the field statement as such:

StreetAddr = customer.StreetAddr + ", " + (customer.Suite ?? "")

However, this code is not so great either because if the "Suite" field is null, then I still got that comma-space ", " hanging out after the "StreetAddr" field. Wish I knew a way to fix that?

Upvotes: 0

arunlalam
arunlalam

Reputation: 1838

var fields = from row in datarows
from field in row
from col in columnnames
where field.Key == col
select new { ColumnName = col, FieldValue = field.Value == null ? string.Empty: field.Value};

Upvotes: 0

Daniel Möller
Daniel Möller

Reputation: 86600

FieldValue = field.Value == null ? "" : field.Value

Upvotes: 4

PSL
PSL

Reputation: 123739

Use ?? operator to return Empty string in case of null

var fields = from row in datarows
from field in row
from col in columnnames
where field.Key == col
select new { ColumnName = col, FieldValue = (field.Value ?? string.Empty) };

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68400

Use the null-coalescing operator

select new { ColumnName = col, FieldValue = field.Value ?? string.Empty };

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

Upvotes: 4

Jon
Jon

Reputation: 437386

Use the null coalescing operator ??:

FieldValue = field.Value ?? ""

Upvotes: 37

Justin Niessner
Justin Niessner

Reputation: 245429

FieldValue = field.Value ?? String.Empty

Upvotes: 6

Related Questions