0

Hi how can I ignore null values in a reader c# in my statement =>

 LegalDesc = reader["legal1"].ToString() + ' ' + 
             reader["legal2"].ToString() + ' ' + 
             reader["legal3"].ToString();

Scenario: if legal2 is a null value the resulting string would be

 legalDesc = legal1 + ' ' + legal3

How could apply iif used in VB?

5
  • 1
    How about reader["legal2"] ?? " "? Commented Mar 18, 2015 at 13:47
  • 1
    How about reader.IsDbNull? Commented Mar 18, 2015 at 13:48
  • would you re-phrase my script...thanks Commented Mar 18, 2015 at 13:49
  • LegalDesc = (reader["legal1"] ?? "") + " " + (reader["legal2"] ?? "") + " " + (reader["legal3"] ?? ""); This is what Soner meant. Commented Mar 18, 2015 at 13:50
  • 'string' is not a valid syntax for string literals Commented Mar 18, 2015 at 13:51

4 Answers 4

1

You could use a collection and String.Join:

List<string> legals = new List<string>();
if(!reader.IsDbNull(reader.GetOrdinal("legal1")))
    legals.Add(reader["legal1"].ToString());
if(!reader.IsDbNull(reader.GetOrdinal("legal2")))
    legals.Add(reader["legal2"].ToString());
if(!reader.IsDbNull(reader.GetOrdinal("legal3")))
    legals.Add(reader["legal3"].ToString());
LegalDesc = string.Join(" ", legals); 

Of course you could also make the code more elegant by using a custom extension method:

public static string SafeGetString(this SqlDataReader reader, int colIndex)
{
   if(!reader.IsDBNull(colIndex))
       return reader.GetString(colIndex);
   else 
       return string.Empty;
}

Now you can use:

string[] legals = { reader.SafeGetString(0), reader.SafeGetString(1), reader.SafeGetString(2) };
LegalDesc = string.Join(" ", legals.Where(s => !string.IsNullOrEmpty(s))); 

This presumes that it's actually a string column and the column ordinal positions are from 0 to 2. If that's not the case use above shown reader.GetOrdinal approach to detect them.

Sign up to request clarification or add additional context in comments.

9 Comments

you can shorten the code with a for loop. reader["legal" + i]
I am receiving an error for the .isdbnull is highlighted red in VS. The data is coming from excel sheet calling the class to load inside the Grid...
@RezoMegrelidze: but that will fail as soon as OP changes the column names or don't want to include all but only specific numbers.
@Jake: maybe because you haven't noticed that i've already fixed a bug. reader.IsDbNull takes an int for the ordinal position of the column(so the index).
public static string SafeGetString(this SqlDataReader reader, int colIndex) { if(!reader.IsDBNull(colIndex)) return reader.GetString(colIndex); else return string.Empty; }
|
0

Using a simple extension method:

public static string ValueOrEmpty(this object source) 
{
     return source == null ? string.Empty : source.ToString();
}

var values = new[] { reader["legal1"],reader["legal2"],reader["legal3"] };
LegalDesc = string.Join(" ", 
                        values.Select(x => x.ValueOrEmpty())
                              .Where(x => x != string.Empty));

Comments

0

First

Do Not do string concatenation like that, every time you concatenate, it creates a new instance of string because string is Immutable. There is a C# class that handles appends and it's StringBuilder

So try implementing it like this

StringBuilder builder = new StringBuilder();
builder.Append(reader["legal1"])
    .Append(" ")
    .Append(reader["legal2"])
    .Append(" ")
    .Append(reader["legal3"]);
Console.WriteLine(builder.ToString());
Console.ReadKey();

This way, you don't even need to check if it's null.

3 Comments

True stringbuilder is the way to go, but if you are only ever going to concatenate three pieces of string, the improvement is minuscule to the point that in a lot of places it could be ignored. stackoverflow.com/questions/73883/string-vs-stringbuilder
@Shekhar true also, but the added benefit here is the null checking being removed.
I disagree on StringBuilder usage for short things like this (string.Concat is better) and in any case we are talking of micro-optimizations that have no sense here, however this doesn't answer the question.
0

Hi I just to want rephrase my problem...

how can view a value to a LegalDesc = reader["legal1"].ToString() if legal1 is null?

I am viewing my result in a grid and so the grid shows NULL in the cell. The result should be a blank space instead of NULL.... in VB net I could use the IIf function if null then blank space...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.