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
?
in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer.
If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.
NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false". Save this answer.
LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.
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"
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With