2010-08-27 79 views
3

我的查詢的返回類型是IEnumerable<XElement>。我怎樣才能將結果數據轉換爲XElement類型?可能嗎?有人能幫助我理解這一點。將IEnumerable <XElement>轉換爲XElement

var resQ = from e in docElmnt.Descendants(xmlns + Constants.T_ROOT) 
          .Where(x => x.Attribute(Constants.T_ID).Value == "testid") 
      select e; 

我必須將resQ作爲參數傳遞給下面的函數。爲了做到這一點,我必須將resQ轉換爲XElement類型。

Database.usp_InsertTestNQuestions(tid, qId, qstn, ans, resQ); 

回答

7

只要你的查詢只返回一個結果,你可以調用單()或結果優先()(也沒有必要的額外的查詢語法往上頂):

// Use if there should be only one value. 
// Will throw an Exception if there are no results or more than one. 
var resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT) 
        .Single(x => x.Attribute(Constants.T_ID).Value == "testid"); 

// Use if there could be more than one result and you want the first. 
// Will throw an Exception if there are no results. 
var resQ = docElmnt.Descendents(xmlns + Contants.T_ROOT) 
        .First(x => x.Attribute(Constants.T_ID).Value == "testid"); 

如果您希望在沒有拋出異常的情況下未返回查詢結果時處理此案例,則可以使用SingleOrDefault(如果您獲得多個結果,它仍會拋出異常)或FirstOrDefault

+0

請注意,如果集合返回多於一個元素,則可以調用First()而不產生異常。 – kbrimington 2010-08-27 18:51:11

+0

這就像魅力。謝謝Justin – BumbleBee 2010-08-27 19:18:59

1

您可以迭代查詢中的每個元素,然後使用您的枚舉器調用該方法。

resQ.ToList().ForEach(e => ...func...); 
1

除了Justin的答案,你可能要允許返回0元素或其他一些條件。

在這種情況下,簡單地做:

IEnumerable<XElement> resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT) 
        .Where(x => x.Attribute(Constants.T_ID).Value == "testid"); 
if(resQ.Count() == 0) { 
    //handle no elements returned 
} else if(resQ.Count() > 1) { 
    //handle more than 1 elements returned 
} else { 
    XElement single = resQ.Single(); 
} 

大多數我覺得最好不要拋出error--除非恰好具有1時返回真的很重要。

+0

我在某處讀到.Any()更好用。然後.Count()...可能在Eric Lippert的博客上。 – asawyer 2010-08-27 21:25:01

相關問題