2011-08-15 19 views
1

試圖用這樣的查詢:獲取的LINQ查詢返回空值,如果兩個變量不相等

var checkName = from nn in xdoc.Root.Elements("string") 
         where nn.Attribute("id").Value.Equals(newTag) 
         select thisbool = true; 

要看看,在我的XML,存在一個節點string其中屬性值id等號這個字符串變量newTag。如果不存在這樣的string節點,我想返回null或東西,我可以檢查直接使用下面的if語句,這樣我可能會禁止特定的變化進行,即

if (thisbool) 
     { 
      MessageBox.Show("The string ID you entered is already in use. Please enter a different string ID."); 
      tagBox.Text = undoTag; 
      return; 
     } 

這是我目前的設置。我也嘗試只選擇nn和使用if(nn != null),但似乎沒有任何工作。我很抱歉,如果這是一個新問題 - 我正在進入一點時間緊縮,我確實試圖找到一個答案,並測試了45分鐘-1小時的事情。

回答

2

此查詢將只列出符合你條件的元素:

var checkName = from nn in xdoc.Root.Elements("string") 
         where nn.Attribute("id").Value.Equals(newTag) 
         select nn; 

然後你的if語句是檢查一樣簡單,如果任何這樣的元素存在:

if (checkName.Any()) 
{ 
    // Code if condition is met by any tag here 
} 

如果您真的需要一個bool相反,你可以結合查詢,像這樣:

bool anyMatches = xdoc.Root.Elements("string") 
        .Where(x => x.Attributes("id").Value.Equals(newTag)).Any(); 

最後,爲了完整性起見,你可以移動從Where()謂詞到Any()

bool anyMatches = xdoc.Root.Elements("string") 
         .Any(x => x.Attributes("id").Value.Equals(newTag)); 

我pesonally喜歡前兩種方法中的一種,因爲我認爲他們拼出更清楚發生了什麼事情。當然,你最喜歡的是你。

+0

沒有需要'Where'的頂部,'Any'具有過載,需要一個謂語。 –

+0

@Yuriy我知道;實際上我發現它使用'Where()'方法更具可讀性,因爲它用語言陳述了Any()'過載實際上在做什麼。性能影響非常小,因爲實際元素的產生和測試是相同的。事實上,我更喜歡我的第一個建議,因爲現在很清楚我的順序是「符合某些條件的元素」,而且我的條件是「是否存在這樣的元素?」 – dlev

+0

我可以看到,我個人更喜歡'myEnumerable.Any(e匹配這個)'的措辭。 –

1

只是把我的頭

from n in source 
let x = n.Prop1 
let y = n.Prop2 
select (x == y) ? value : null; 
2
bool thisbool = xdoc.Root.Elements("string") 
    .Any(e => e.Attribute("id").Value == newTag); 
1
bool anySuchElementExists 
    = xdoc.Root.Elements("string") 
     .Any(e => e.Attribute("id").Value == newTag);