2013-06-21 134 views
1

我有這樣的C#代碼:如何將默認值設置爲「n/a」,如果它爲空?

 var result = 
      from entry in feed.Descendants(a + "entry") 
      let content = entry.Element(a + "content") 
      let properties = content.Element(m + "properties") 
      let notes = properties.Element(d + "Notes") 
      let title = properties.Element(d + "Title") 
      let partitionKey = properties.Element(d + "PartitionKey") 
      where partitionKey.Value.Substring(2, 2) == "06" && title != null && notes != null 
      select new Tuple<string, string>(title.Value, notes.Value); 

如果我選擇筆記它僅= NULL

不是這樣做如何設置notes.Value的值在元組爲「n/a「如果notes.Value是空的?

回答

2

可以使用null coallescing operator??

select new Tuple<string, string>(title.Value, notes.Value ?? "n/a"); 

注意你也可以使用Tuple.Create代替元組構造:

select Tuple.Create(title.Value, notes.Value ?? "n/a"); 
7

可以使用null coalescing operator

notes.Value ?? "n/a" 

哪說:「如果不是空值,則獲得價值,否則我們次要論據。「

+0

+1解釋上! –

1

Enumerable String的情況下,你可以使用空合併運算符在let表達水平具有默認的空

let notes = properties.Element(d + "Notes") ?? "n/a" 
let title = properties.Element(d + "Title") ?? "n/a" 

的情況下,那麼where子句改寫爲

where partitionKey.Value.Substring(2, 2) == "06" 
    select new Tuple<string, string>(title.Value, notes.Value); 

正如指出的,在XElement的情況下,您可以交替使用

where partitionKey.Value.Substring(2, 2) == "06" 
    select new Tuple<string, string>(title.Value??"n/a", notes.Value??"n/a"); 
+0

??可以應用於XElement和字符串:-( – Alan2

+0

@Gemma,我沒有測試過XElement,但是使用了Enumerable String。如果你認爲它會中斷,那麼就去除邏輯where和select子句,我修改了代碼。 – Nair

相關問題