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

entity-framework linq

Question

It seems to work for the ternary operator, but this is TRUE or FALSE and I need to have more than 2 alternatives. I'm attempting to incorporate an IF inside my LET in LINQ but I can't get it to work.

I believe this clarifies it.

I basically have a select that pulls objects from a database using joins. Then, based on the kind of items, I get the status for each record, but I must connect data from many databases. 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
}

Anyone have suggestions on how to implement a standard IF so I can choose which STATUS (let) I want to run?

I appreciate you.

1
2
6/14/2012 9:10:53 AM

Accepted Answer

That is possible using 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;
}

You could also do it this way if you are just utilizing the status for the StatusText.

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) There is currently just one ternary operator in C#, which is the conditional operator. It accepts three inputs.

9
6/14/2012 9:18:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow