user3560094
user3560094

Reputation:

Passing a null value as a string

I have the following terrible code:

CurrentInvoice = invoiceTable.AsEnumerable()
                    .First().ItemArray
                    .Where(a == null, a = (int a).Tostring("null"))
                    .Select(i => i.ToString())
                    .ToArray();

I'm trying to use the "Where" method to pass any null values as a physical string that reads "null", without breaking the rest of the line. Am I going to get anywhere using the "Where" method?

Upvotes: 1

Views: 178

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062855

I think you're over-complicating it by trying to use LINQ here; this looks like a DataTable's first row, in which case:

object[] arr = invoiceTable.Rows[0].ItemArray;
for(int i = 0 ; i < arr.Length ; i++) {
    if(arr[i] == null || arr[i] is DBNull) arr[i] = "null";
}

This is easier to write, easier to understand, and much more efficient.

Edit: if the final result is (comments) intended to be a string[], then:

object[] arr = invoiceTable.Rows[0].ItemArray;
string[] result = Array.ConvertAll(arr,
    val => (val == null || val is DBNull) ? "null" : val.ToString());

Upvotes: 1

Omar
Omar

Reputation: 16623

I don't understand what you're really asking for, but maybe you need something like:

CurrentInvoice = invoiceTable.AsEnumerable()
                    .First().ItemArray
                    .Select(x => x == null ? "null" : x) //or x ?? "null" for more info check the null coalescing operator
                    .ToArray();

So you "convert" string from null to "null". As you see you don't need to filter the ItemArray by using the Where() statement.

Upvotes: 2

PulseLab
PulseLab

Reputation: 1579

The Where statement filters the array, but you need to do a transform on each cell, which is a Select statement.

You need something like .Select(a => a ?? "null") instead of the Where I think?

Upvotes: 4

Related Questions