-2

I want to create an if/else statement in this case :

        var controls= _listControls
            .Select(
                control => new
                {
                    Name,
                    Quantity,
                    Valid = isValid
                    ? sp.GetInfos(ID).SerialNumber.ToString()
                    : string.Empty
                })
            .ToList();

I just want to check if sp.GetInfos(ID).SerialNumber.ToString()is null in the statement and say if it's not null ? DoThings() : DoThings() .

Thanks

Memo
  • 213
  • 3
  • 13
  • 1
    How to make simple statement unreadable? Put it into one-liner and split it into multiple liines. – Sinatr Apr 05 '16 at 13:00

2 Answers2

1

You can use ternary operators inside other ternary statements like this

Valid = isValid
? string.IsNullOrEmpty(sp.GetInfos(ID).SerialNumber?.ToString())
? string.Empty 
: sp.GetInfos(ID).SerialNumber.ToString()
: string.Empty

N.B. The SerialNumber?.ToString() is a null conditional operator, you can read more about it here

Community
  • 1
  • 1
Alfie Goodacre
  • 2,753
  • 1
  • 13
  • 26
  • 1
    you can replace lines 2-3 with `string.IsNullOrEmpty` – trashr0x Apr 05 '16 at 12:58
  • ToString() will never return null. But if SerialNumber is null a NullReferenceException will be thrown. – JoanComasFdz Apr 05 '16 at 13:02
  • I have edited the code so that if SerialNumber is null, null is returned but otherwise it is turned into a string – Alfie Goodacre Apr 05 '16 at 13:04
  • this violate the principle: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ( cit ) – Felice Pollano Apr 05 '16 at 13:15
  • While this is true and I agree to an extent as an if would be better here, the OP asked specifically for the answer using ternary, I can add a second version with if statements if you would like, or point to Valentin's answer – Alfie Goodacre Apr 05 '16 at 13:18
0

You can encapsulate all logic in a helper method. As I consider it's more readable and also you are able to test this method separately.

string Valid(....)
{
    if (isValid)
    {
        if (sp.GetInfos(ID).SerialNumber == null)
        {
            ....
        }
        else
        {
            ..
        }
    }

    return string.Empty;
}

And then simply call this method inside LINQ query

var controls = _listControls
        .Select(
            control => new
            {
                Name,
                Quantity,
                Valid = Valid (...) 
            })
        .ToList();
Valentin
  • 5,380
  • 2
  • 24
  • 38