为什么Equals不能像预期的那样工作

本文关键字:工作 Equals 不能 为什么 | 更新日期: 2023-09-27 18:16:03

在阅读了大约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'

任何帮助都是感激的!

为什么Equals不能像预期的那样工作

听起来你想这么做:

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;

还没有编译,所以它可能有一个或两个错误,但它肯定是沿着这些行:)

等号右侧的"from cd"返回符合条件的所有结果,而不仅仅是一个。