5

I have the following code:

    [DisplayName("Created")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? Created { get; set; }

    [DisplayName("Modified By")]
    public string ModifiedBy { get; set; }

    [DisplayName("Modified")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? Modified { get; set; }

        from d in data
        select new Content.Grid
        {
            PartitionKey = d.PartitionKey,
            RowKey = d.RowKey,
            Order = d.Order,
            Title = d.Title,e
            Created = d.Created,
            CreatedBy = d.CreatedBy,
            Modified = d.Modified,
            ModifiedBy = d.ModifiedBy
        };

There is a possibility that d.Created, d.CreatedBy, d.Modified and d.ModifiedBy may be null.

How can I make it so that if they are null then the select returns n/a for the CreatedBy and ModifiedBy and returns the date January, 1, 2012 for the Created and Modified?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

10

You can use the null-coalescing operator (??) to give default values for nullable value types or reference types:

from d in data
select new Content.Grid
{
    PartitionKey = d.PartitionKey,
    RowKey = d.RowKey,
    Order = d.Order,
    Title = d.Title,e
    Created = d.Created ?? new DateTime(2012,1,1),
    CreatedBy = d.CreatedBy ?? "n/a",
    Modified = d.Modified ?? new DateTime(2012,1,1),
    ModifiedBy = d.ModifiedBy ?? "n/a"
};
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • This looks very good. I have another select with a join where I use: Type = t == null ? null : t.Value, Could I also use this operator for that? – Alan2 Aug 19 '12 at 06:25
  • No this is a different construct. null-coalescing is for the case when you have `null` but you want something else than `null`. In your join if you have `null` you still want `null` otherwise you want something else. So only cases like this: `Type = t == null ? SomeDefaultType : t` can be reformulated to `Type = t ?? SomeDefaultType` – nemesv Aug 19 '12 at 06:29
  • Thanks this works , initially i tried to use constructor in my class to set default values to properties using [this](http://stackoverflow.com/a/43594/2218697) example , but it didn't work why ? – Shaiju T Sep 25 '16 at 08:33
  • How do you assign a boolean value of false if d.boolfield == true? – Oracular Man Feb 17 '18 at 02:23