user49126
user49126

Reputation: 1863

Tricky if statement

Is it possible to convert this if statement into a one line statement ?

        if (value != DBNull.Value)
        {
            dic.Add(columnName);
        }
        else if (!skipNullValues)
        {
            dic.Add(columnName);    
        }

Upvotes: 1

Views: 208

Answers (4)

mellodev
mellodev

Reputation: 1607

If you edit to include why making it a single line will help you might get a more suitable answer. Here are a few different approaches you could take..

First off, in a single line as you requested:

if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues)) { dic.Add(columnName); }

Alternatively you might want to look into using ternary operators if you need something more compact.

var result = (istrue) ? (return valIfTrue) : (return valIfFalse);

More info on ternary operators: http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx

Most likely (depending on your situation) you should consider creating a method similar to this:

public void AddColumnToDic(object value, string columnName) 
    bool skipNullValues = false; // todo: read from configuration
    if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues))
    {
        dic.Add(columnName);
    }
}

and simply call it for every cell value you encounter.

Upvotes: 0

ABH
ABH

Reputation: 3439

if (!(value == DBNull.Value && skipNullValues))
    dic.Add(columnName);

Upvotes: 1

Ian
Ian

Reputation: 34489

Use a logical OR:

if (value != DBNull.Value || !skipNullValues)
   dic.Add(columnName);

I would keep the addition on a new line for clarity, although for a simple statement like this you're probably alright to drop the curly brackets. You do need to be careful if you try to add more logic in the future though obviously in the branch of the if.

Upvotes: 2

George Duckett
George Duckett

Reputation: 32428

if (value != DBNull.Value || !skipNullValues) dic.Add(columnName);

Upvotes: 8

Related Questions