繁体   English   中英

为什么Equals没有按预期工作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM