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?

Steve
  • 213,761
  • 22
  • 232
  • 286
Jake
  • 93
  • 7

4 Answers4

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • you can shorten the code with a for loop. reader["legal" + i] – Rezo Megrelidze Mar 18 '15 at 13:53
  • 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... – Jake Mar 18 '15 at 13:53
  • @RezoMegrelidze: but that will fail as soon as OP changes the column names or don't want to include all but only specific numbers. – Tim Schmelter Mar 18 '15 at 14:00
  • @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). – Tim Schmelter Mar 18 '15 at 14:01
  • public static string SafeGetString(this SqlDataReader reader, int colIndex) { if(!reader.IsDBNull(colIndex)) return reader.GetString(colIndex); else return string.Empty; } – Jake Mar 18 '15 at 14:08
  • @Jake: since that is an extension method i guess that you have added the code in a `static class` that is accessible from the code where you use it?! – Tim Schmelter Mar 18 '15 at 14:10
  • @Jake: what code are you showing there? It's not related to mine. – Tim Schmelter Mar 18 '15 at 14:34
  • public UserViewModel(DataTableReader reader) { RollNumber = reader["roll_nt"].ToString(); Owners = reader["owner_2"].ToString(); LegalDesc = reader["legal1"].ToString() + ' ' + reader["legal3"].ToString() + ' ' + reader["legal3"].ToString(); } } – Jake Mar 18 '15 at 14:59
  • The data is coming from excel file calling this script to view inside the Grid... – Jake Mar 18 '15 at 15:00
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));
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
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.

DevEstacion
  • 1,947
  • 1
  • 14
  • 28
  • 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. http://stackoverflow.com/questions/73883/string-vs-stringbuilder – Shashank Shekhar Mar 18 '15 at 14:01
  • @Shekhar true also, but the added benefit here is the null checking being removed. – DevEstacion Mar 18 '15 at 14:03
  • 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. – Steve Mar 18 '15 at 14:06
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...

Jake
  • 93
  • 7