views:

118

answers:

2

I have this block of code that eventually get serialized to JSON, for use in the Jquery FullCalender plugin. The ToUnixTimeSpan method taskes in a DateTime object and returns the number of seconds since 1970.

DateEnd could be null. In this block of code how do i test for the null and skip the end = ToUnixTimespan(e.DateEnd), if DateEnd is null? is there a C# equivalent to the groovy safe operator?

var listEvents = from e in eventRepository.GetAllEvents()

                         select new
                         {
                             id = e.EventID,
                             title = e.EventTitle,
                             start = ToUnixTimespan(e.DateStart),

                             end = ToUnixTimespan(e.DateEnd),
                             url = "/Events/Details/" + e.EventID
                         };

Further info about the ToUnixTimespanMethod:

private long ToUnixTimespan(DateTime date)
    {
        TimeSpan tspan = date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0));
        return (long)Math.Truncate(tspan.TotalSeconds);
    }
+6  A: 

Well, how about:

end = e.DateEnd == null ? (long?) null : ToUnixTimespan(e.DateEnd)

It's hard to say for sure as we don't know the type returned by ToUnixTimespan.

Jon Skeet
@Jon How about [end = e.DateEnd ?? ToUnixTimespan(e.DateEnd);] ?
Rafael Belliard
@Rafael E. Belliard, That calls ToUnixTimespan if e.DateEnd is null, which is pretty much the opposite of what @Doozer1979 wants.
strager
ooooh, challenging the legend that is "THE SKEET"!
Neurofluxation
@Rafael: What strager said, *and* it assumes that the desired type of `end` is the same as the type of `e.DateEnd` which I suspect it isn't...
Jon Skeet
Thanks all. Jon using that line of code results in the following error: cannot convert from 'System.DateTime?' to 'System.DateTime'. Thanks for the help, still relatively new to C#
Doozer1979
@Dozzer: I thihnk the last part wants to be: `ToUnixTimespan(e.DateEnd.Value)`
James Curran
+3  A: 

Wait-a-minute... Why am I wasting this on a comment, when I could be leveraging Jon's work for some rep.. ;-)

end = e.DateEnd == null ? (long?) null : ToUnixTimespan(e.DateEnd.Value) 

That should solve the "cannot convert from 'System.DateTime?' to 'System.DateTime'." error.

James Curran
Much obliged to you both, this did the trick.
Doozer1979