2012-04-27 97 views
1

我正在使用VB中的LINQ to XML(儘管C#中的答案也很棒)。首先,我的代碼起作用,所以這不是關鍵。然而,我不禁想到,我正在用條件邏輯做什麼,應該已經可以使用LINQ查詢本身來做。LINQ to XML,有沒有更好的方法來確定一個元素是否存在於列表中?

下面是我得到了什麼:

 'Get the Description elements in the ResultData section where the value is "Op Code" 
     Dim opCodes As List(Of XElement) = (From c In xdoc.Descendants("ResultData").Descendants("Description") 
       Where c.Value = "Op Code" 
       Select c).ToList() 

     If opCodes.Count > 0 Then 
      'Get the sibling XElement of the first "Description" XElement (there should be only one) by using the parent 
      sOperator = Convert.ToString(((From c In opCodes 
        Select c).FirstOrDefault().Parent).<Value>.Value) 
     Else 
      sOperator = "Not Available" 
     End If 

請不要太挑剔我的定位節點 - 的XML文件是由第三方測試設備產生的兄弟的方法,這是隻有通用的方式來獲取我需要的值。我在這裏尋找的是處理If塊的更好方法。

提供任何想法將不勝感激。

回答

1

這聽起來像你想(C#):

string operator = xdoc.Descendants("ResultData") 
         .Descendants("Description") 
         .Where(x => x.Value == "Op Code") 
         .Select(x => x.Parent.Element("Value").Value) 
         .FirstOrDefault() ?? "Not available"; 

,它假定我理解正確的話,那你只是試圖讓兄弟姐妹中的文本「值」元素。

我不認爲空凝聚(??)操作符存在VB,但你可以採取一切儘可能FirstOrDefault,然後只是有一個「如果這沒有什麼,將其設置爲不可用」檢查。

+0

@dasblinkenlight:「雖然在C#中的答案也很好,」 – 2012-04-27 14:45:39

+0

+1偉大的C#答案:) – dasblinkenlight 2012-04-27 14:46:02

+1

感謝Jon,這是我需要的線索。此外,如果它幫助其他人VB的空合併運算符只是如果(nullableType,altValue)。 – 2012-04-27 20:43:28

相關問題