LINQ is so much fun and makes things so much easier to accomplish. It's also gaining quite a bit of acceptance and it's evolving too with things like: LINQ to JavaScript and LINQ to JSON. I've been playing with LINQ quite a bit and recently I needed to generate a CASE statement with LINQ to SQL. It was fairly easy to accomplish since LINQ is so darn cool! Here is what I came up with:


var gimmeh_gimmeh =
 from t in db.sc_Timeslots
 where (t.starttime.Minute % 5 == 0) || (t.starttime.Minute % 10 == 0)
 select new
 {
  t.id,
  t.starttime,
  interval = (t.starttime.Minute % 5 == 0) ? "5 Minutes" : "10 Minutes"
 };

The line: "interval = ..." generates a CASE statement as shown below.


SELECT [t0].[id], [t0].[starttime],
    (CASE
        WHEN (DATEPART(Minute, [t0].[starttime]) % @p4) = @p5 THEN CONVERT(NVarChar(10),@p6)
        ELSE @p7
     END) AS [interval]
FROM [dbo].[sc_Timeslot] AS [t0]
WHERE ((DATEPART(Minute, [t0].[starttime]) % @p0) = @p1) OR ((DATEPART(Minute, [t0].[starttime]) % @p2) = @p3)

You can have multiple CASE statements or even concat them like so:


  interval = ((t.starttime.Minute % 5 == 0) ? "5 Minutes" : "10 Minutes") + ((t.id == 1) ? " (Master ID)" : "")

Which will generate the Case statement below (hey I'm starting to rhyme):


    (CASE
        WHEN (DATEPART(Minute, [t0].[starttime]) % @p4) = @p5 THEN CONVERT(NVarChar(22),@p6)
        ELSE @p7 + (
            (CASE
                WHEN [t0].[id] = @p8 THEN @p9
                ELSE CONVERT(NVarChar(12),@p10)
             END))
     END) AS [interval]

You can also nest the CASE statements... but I think by now you're clever enough to figure that out on your own.

Enjoy!

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Comments

carzybasketball People's Republic of China

Saturday, May 31, 2008 9:54 AM

carzybasketball

hellow,i write a case linq like you said,but i can't work,i don't know why.
my code is show below
var info = from userInfo in db.TuserInfo

            select new TuserInf

{

UserName=info.UserNmae,

Sex=info.Sex=="M"?"man":"woman"

};

this.listView1.DataContext=info.ToList();

if i write linq like that,it will happen a error in last sentence!

it will ok when i write like following:

var info = from userInfo in db.TuserInfo

            select new TuserInf

{

UserName=info.UserNmae,

Sex=info.Sex

};

this.listView1.DataContext=info.ToList();

Result is below(the data of database is also store likethis)

UserName                Sex

"Jack"                     "M"

"Tom"                      "M"

"Marry"                   "W"

---------------------------------------------------------

but i want the data result like this:

UserName                Sex

"Jack"                     "Man"

"Tom"                      "Man"

"Marry"                   "Woman"

how can i do?
My MSN is "zhongnba@hotmail.com"

Denny United States

Friday, June 06, 2008 3:35 AM

Denny

Try surrounding your expression in parenthesis like this:

Sex = (info.Sex == "M") ? "man" : "woman"

Gabriel Canada

Thursday, July 10, 2008 10:43 PM

Gabriel

I getting a weird error when I have two CASE statements in my LINQ statement. Here is the example:

var results2 = (from g in this.db.Groups
                            where g.Name.ToLower().Contains(KeyWord)
                            select new
                            {
                                Type = "Group",
                                Id = g.Id.ToString(),
                                Name = g.Name,
                                Description = g.Description,
                                PictureUrl = g.PictureUrl,
                                State = "",
                                Country = ""
                            }).Concat(
                            from mp in this.db.MemberProfiles
                            where mp.FullName.ToLower().Contains(KeyWord)
                            select new
                            {
                                Type = "MemberProfile",
                                Id = mp.UserId.ToString(),
                                Name = mp.FullName,
                                Description = "",
                                PictureUrl = mp.PictureUrl,
                                State = (mp.StateId.HasValue) ? mp.State.Name : "N/A",
                                Country = (mp.CountryId.HasValue) ? mp.Country.Name : "N/A"
                            }).OrderBy(sr => sr.Name);


Now, this gives me an error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

But if I take one of the CASE statement. Either the Country or the State, it works fine...

Any ideas why it does this?

Thanks,

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Denny Dot Net

Mmmmmm.... ASP.NET Code