views:

1898

answers:

2

How do I do a Case WHEN in Linq to SQL (vb.net please).

In SQL it would be like this:

SELECT 
CASE
  WHEN condition THEN trueresult
  [...n]
[ELSE elseresult]
END

How would I do this in Linq to SQL?

+1  A: 

I haven't tried this but you may be able to do something like:

Dim query = From tbl In db.Table _
            Select result =_
                If(tbl.Col1 < tbl.Col2,"Less than",_
                    If(tbl.Col1 = tbl.Col2,"Equal to","Greater than"))

You would just need to keep nesting the If functions to handle all of your cases.

You can find more examples of various queries at http://msdn.microsoft.com/en-us/library/bb386913.aspx

tvanfosson
Thanks! I guess this will have to do.
EdenMachine
+1  A: 

Check This Out

var data = from d in db.tb select new {

CaseResult = (

d.Col1 == “Case1” ? "Case 1 Rised" :

d.Col1 == “Case2” ? "Case 2 Rised" :

"Unknown Case")

};

Please Note that [ ? Symbol = then] , [ : Symbol = Or].

Regards.

Amr M. Tareef
EXCELLENT! thanks for the update!
EdenMachine