2

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

4 回答 4

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;
于 2013-05-29T22:25:13.277 回答
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;
于 2013-05-29T22:23:14.243 回答
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;

还没有编译,所以它可能有一两个错误,但它肯定在这些线上的某个地方:)

于 2013-05-29T22:25:15.430 回答
1

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

于 2013-05-29T22:26:58.080 回答