LINQ to SQL and Case statement

Working with LINQ I realized that I had to use the simple case statement in my SQL query. There is no special keyword for this. To create a case statement like structure you will have to do it in the select section of the query.

Below is an example of the usage of the case statement in LINQ.

var t = from n in idc.categories
            select new
            {
                        catName =
                        (n.id==1 ? “Cat1” :
                        n.id==2 ? “Cat2” :
                        n.id==3 ? “Cat3” : “Unknown Category”
                        )

            };

Here in the above code we are using multiple cases for value 1, 2 and 3 and the default value is given at the last.

Vikram

No Comments