2013-05-29 65 views
2

在閱讀了大約40-50個問題和答案(我嘗試了很多東西)之後,所有的答案都稍微有些偏離了,但我還是無法理解這種方式如何工作:爲什麼Equals沒有按預期工作

IEnumerable<string> textSegs = from cd in cds 
     where cd.Artist.Equals("Dream Theater") 
     select cd.Artist; 

foreach(string s in textSegs) 
    Console.Write("\nTrack: " + s); 

//This outputs: 'Track: Dream Theater' 

現在,至於其他部分:

IEnumerable<string> textSegs = from seg in myXMLDoc.Descendants("name") 
    where ((string)seg).Equals("Dream Theater") 
    select (string)seg; 
//This puts: exactly what I need 

然後我想這會做魔術:

IEnumerable<string> textSegs = from seg in myXMLDoc.Descendants("name") 
    where ((string)seg).Equals(from cd in cds 
           where cd.Artist.Equals("Dream Theater") 
           select cd.Artist) 
    select (string)seg; 

//This outputs: Everything that is inside the XMLDoc (no filter applied) 

至於這個代碼的格式。恐怕它必須是這樣的(賦值)。我試圖將子查詢投射到一個字符串,但它告訴我:

Cannot convert type 'IEnumerable<string>' to 'string' 

任何幫助表示讚賞!

+2

'from ... select'是一組字符串。你不能檢查它是否等於單個字符串。 – SLaks

回答

2

你基本上要問,如果一組數據中包含的數據的另一個子集:

var artistQuery = from cd in cds 
        where cd.Artist.Equals("Dream Theater") 
        select cd.Artist; 

IEnumerable<string> textSegs = from seg in myXMLDoc.Descendants("name") 
           where artistQuery.Contains((string) seg) 
           select (string)seg; 

我已經打破了每個查詢上面顯示的步驟。你也可以把它寫成一個語句:

IEnumerable<string> textSegs = from seg in myXMLDoc.Descendants("name") 
           where (from cd in cds 
             where cd.Artist.Equals("Dream Theater") 
             select cd.Artist).Contains((string) seg) 
           select (string)seg; 
+0

非常感謝! –

3

就像你正在試圖做這聽起來對我說:

IEnumerable<string> textSegs = 
    from seg in myXMLDoc.Descendants("name") 
    where ((string)seg).Equals(
     (from cd in cds 
      where cd.Artist.Equals("Dream Theater") 
      select cd.Artist).First()) 
    select (string)seg; 

還是這個,這是一個有點更容易閱讀:

IEnumerable<string> textSegs = 
    from seg in myXMLDoc.Descendants("name") 
    let artist = 
     (from cd in cds 
      where cd.Artist.Equals("Dream Theater") 
      select cd.Artist).First() 
    where ((string)seg).Equals(artist) 
    select (string)seg; 
1

嘗試加入,我想不出一個更清潔的方法來做到這一點:

from seg in myXMLDoc.Descendants("name") 
join cd in cds 
    on (string)seg equals cd.Artist 
where cd.Artist.Equals("Dream Theater") 
select (string)seg; 

沒有編譯,所以它可能有一個錯誤或兩個,但它肯定是沿着這些線的某處:)

1

您在等式右側的「從cd」返回所有符合條件的結果,而不僅僅是一個。

相關問題