user441521
user441521

Reputation: 6998

Change empty string to zero in list

I have a list:

IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());

Some of these values are empty strings. I want to change all the empty strings to "0". Is there a 1 line linq command I can use to do that?

Upvotes: 1

Views: 92

Answers (4)

Adrien Piquerez
Adrien Piquerez

Reputation: 1044

Try this :

fields.Select(s => String.IsNullOrEmpty(s) ? "0" : s);

Upvotes: -2

DLeh
DLeh

Reputation: 24395

Don't forget the ToString() on field if ItemArray doesn't contain strings.

IEnumerable<string> fields = row.ItemArray.Select(field => 
    string.IsNullOrWhitespace(field.ToString()) ? "0" : field.ToString());

Upvotes: 6

recursive
recursive

Reputation: 86064

You can do it with .IsNullOrEmpty().

IEnumerable<string> fields = 
    from field in row.ItemArray
    let s = field.ToString()
    select string.IsNullOrEmpty(s) ? "0" : s;

Upvotes: 1

ro-E
ro-E

Reputation: 299

IEnumerable<string> fields = row.ItemArray.Select(field => string.IsNullOrEmpty(field) ? "0" : field.ToString());

Upvotes: -1

Related Questions