为什么Equals没有按预期工作

时间:2013-05-29 22:17:20

标签: c# linq linq-to-xml

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

感谢任何帮助!

4 个答案:

答案 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 :(得分: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;

答案 2 :(得分: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;

没有编译,所以它可能有一两个错误,但它肯定是沿着这些方向的某个地方:)

答案 3 :(得分:1)

Equals右侧的“来自cd”会返回符合条件的所有结果,而不只是一个。