LINQ: Using a ternary ( ?: ) with LINQ let is not enough, need an "IF" but can't seem to get it to work

I am trying to include an IF within my LET in LINQ but i can't get it to work, it seems to work for the ternary operator, but this is TRUE or FALSE and i need to have more than 2 options.

I think this explains it well

Basically i have a select which selects items using joins from a DB. Then the i get the status for each record but i have to make a join on separate tables depending on the type from products.type

var tst = from p in products join i in info on p.id equals i.pid

// if p.type = "home" then ...

let status = from s in homestatus
select new { status = s.status }

// if p.type ="offshore" then


let status = from s in offshorestatus
select new { status = s.status }


// if p.type ="internal" then


let status = from s in internalestatus
select new { status = s.status }

select new {
name = p.name,
status = status.StatusText
}

Anybody have any ideas how to do a standard IF so i can select which STATUS (let) i wish to execute.

Thanks in advance

Answers


You can do that with the conditional operator (1)

var tst = from p in products join i in info on p.id equals i.pid

let status = p.type = "home" ? homestatus.Select(s=>s.status) :
             p.type = "offshore" ? offshorestatus.Select(s=>s.status) :
             p.type = "internal" ? internalestatus.Select(s=>s.status) : null
select new {
name = p.name,
status = status != null ? status.StatusText : string.Empty;
}

If you are not using the status for anything else than the StatusText you could also do it like this

var tst = from p in products join i in info on p.id equals i.pid

let status = (p.type = "home" ? homestatus.Select(s=>s.status.StatusText) :
             p.type = "offshore" ? offshorestatus.Select(s=>s.status.StatusText) :
             p.type = "internal" ? internalestatus.Select(s=>s.status.StatusText) : null) ?? string.Empty
select new {
name = p.name,
status = status;
}

(1) A ternary operator is any operator that takes three arguments, of which there at present is only one in C# called the conditional operator


Need Your Help

Unable to load Custom ADO.NET provider for NHibernate

c# postgresql nhibernate devart dotconnect

I am using Devart Postgres driver as the Ado.net provider with NHibernate. Since NHibernate does not support Devart Postgres driver, I wrote a custom driver class based on ReflectionBasedDriver. He...