Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 876
Meow Avatar asked May 10 '13 20:05

Meow


People also ask

Is empty string considered null in C#?

A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.

Is an empty string null?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Can string contains null?

'null' is not valid method argument. String. contains() method does not accept 'null' argument. It will throw NullPointerException in case method argument is null.

Can LINQ select return null?

It will return an empty enumerable. It won't be null.


1 Answers

Use the null coalescing operator ??:

FieldValue = field.Value ?? ""
like image 103
Jon Avatar answered Oct 25 '22 18:10

Jon