How can I make my Linq return values ​​if the selected value is null?

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
        };

It is likely that d.Created, d.CreatedBy, d.Modifiedand d.ModifiedBymay be empty.

How can I make it so that if they are zero, select returns n/afor CreatedByand ModifiedByand returns a date January, 1, 2012for Createdand Modified?

+5
source share
1 answer

You can use the null coalescing operator ( ??) to provide default values ​​for nullable 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"
};
+10
source

All Articles