[英]Why is Equals not working as expected
在閱讀了大約40-50個問題和答案(我已經嘗試了很多事情)之后,盡管所有答案都略有偏離,但我仍然無法理解這是怎么回事:
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'
任何幫助表示贊賞!
聽起來像你正試圖這樣做:
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;
您本質上需要詢問一組數據是否包含另一組數據:
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;
嘗試加入,我想不出更干凈的方法:
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;
還沒有編譯,所以可能有一個或兩個錯誤,但可以肯定地在這些地方:)
Equals右側的“from cd”將返回符合條件的所有結果,而不僅僅是一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.