2012-06-20 22 views
2

我正在學習LINQ並嘗試使用與select子句相關的此示例。select子句中表達式的類型不正確。在「Select」中調用類型推斷失敗

var q = from c in xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true") 
        .Select(n => new { SiteName = n.Element("name").Value}); 

上面的查詢是給我的錯誤:
The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

什麼是錯的INT上述語法?

除了上述,我必須轉換selected選項ToDictionary。如何通過LINQ在同一個查詢中完成?

我在腦海裏想的第三個問題是關於編寫同一個查詢的不同語法(e:下面的第二個寫方法)。什麼語法是首選,爲什麼?

from c in xmlDoc.Descendants 
where c.Attriubute("technical").Value == "true" 
select c.Element("site").Value; 
+1

做了第二個查詢工作,或者它也給你錯誤? –

+1

不太瞭解錯誤,您可以發佈您的示例XML嗎? – Habib

+1

第二個查詢工作 – user1372448

回答

3

1. 你有混合lambda表達式使用LINQ語法。從linq開始,以lambda表達式結束。試試這個

var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true") 
        .Select(n => new { SiteName = n.Element("name").Value}); 

,或者你應該使用整個查詢在LINQ

var q = from c in xmlDoc.Descendants("site") where c.Attribute("technical").Value == "true" 
        select new { SiteName = c.Element("name").Value}; 

2. 只使用ToDictionary在查詢結束

var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true") 
        .Select(n => new { SiteName = n.Element("name").Value,Key= n.Element("id").Value }).ToDictionary(n=>n.Key,l=>l.SiteName); 

N => n.Key將字典和l => l.siteName的關鍵字作爲值。

3. 創建這樣的查詢有兩種方法,一種是使用linq,另一種是使用使用lambda表達式作爲參數的方法。兩者都很容易,linq就像SQL查詢,而方法使用lambda更像是用描述方法操縱數據的簡短手段。我個人喜歡以lambda爲方法導向的方式,因爲它更具有順序可讀性。

+3

你的術語是不正確的,潛在的令人困惑的。 [**這兩種**語法都是** Linq **:一種是「查詢語法」,另一種是「方法語法」](http://msdn.microsoft.com/zh-cn/library/bb397947.aspx) 。 Lambda表達式完全不同。 – AakashM

+0

謝謝@AakashM我忘了提及所有Linq方法都使用lambda表達式。你是對的查詢/方法語法是正確的術語。 –

相關問題