DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Generating a Case Statement in LINQ to SQL

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

Tags: ,
Posted by Denny on Friday, February 08, 2008 5:04 AM
Permalink | Comments (4) | Post RSSRSS comment feed

Comments

carzybasketball People's Republic of China

Friday, May 30, 2008 6:54 PM

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

Thursday, June 05, 2008 12:35 PM

Denny

Try surrounding your expression in parenthesis like this:

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

Gabriel Canada

Thursday, July 10, 2008 7:43 AM

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,

Best Free Porn Videos United States

Thursday, July 16, 2009 8:39 AM

Best Free Porn Videos

Interesting post, i like, i like.

Comments are closed