![](/img/trans.png)
[英]How can I have my Linq select return something different based on a parameter of my method?
[英]How can I make my Linq select return values if the value selected is null?
我有以下代碼:
[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
};
d.Created
, d.CreatedBy
, d.Modified
和d.ModifiedBy
可能為空。
我怎樣才能這樣做,如果它們為null,那么select為CreatedBy
和ModifiedBy
返回n/a
並返回Created
和Modified
January, 1, 2012
?
您可以使用null-coalescing運算符 ( ??
)為可空值類型或引用類型提供默認值:
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"
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.