如何在C#中访问它?

时间:2010-12-23 15:24:21

标签: c# xml linq

private void LoadSubforums(Forum forum, XElement subforumsXML)
{
    forum.Subforums = (from forumItem in subforumsXML.Descendants("forum")
                      select new Subforum()
                      {
                          ID = (string)forumItem.Element("id"),
                          Name = (string)forumItem.Element("name"),
                          URL = (string)forumItem.Element("url"),
                          Description = (string)forumItem.Element("description"),
                          Type = (string)forumItem.Element("type"),
                          TopicCount = (string)forumItem.Element("topics"),
                          ReplyCount = (string)forumItem.Element("replies"),
                          LastPost = ParseLastPost(forumItem.Element("lastpost")),
                          IsRedirect = How can I access the LastPost attribute here? :S
                      }).ToList();
}
}

IsRedirect类的Subforum属性取决于LastPost属性中的值。

我是否可以从Linq查询中访问此属性?

编辑:

这就是我要做的事情:

forum.Subforums = (from forumItem in subforumsXML.Descendants("forum")
                               let lastPost = ParseLastPost(forumItem.Element("lastpost"))
                               select new Subforum()
                               {
                                   ID = (string)forumItem.Element("id"),
                                   Name = (string)forumItem.Element("name"),
                                   URL = (string)forumItem.Element("url"),
                                   Description = (string)forumItem.Element("description"),
                                   Type = (string)forumItem.Element("type"),
                                   TopicCount = (string)forumItem.Element("topics"),
                                   ReplyCount = (string)forumItem.Element("replies"),
                                   LastPost = lastPost,
                                   IsRedirect = if(lastPost.ID == null) ? true ; false
                               }).ToList();

但是这段代码没有编译。

1 个答案:

答案 0 :(得分:3)

forum.Subforums = (from forumItem in subforumsXML.Descendants("forum")
                   let lastPost = ParseLastPost(forumItem.Element("lastpost"))
                   select new Subforum()
                   {
                       ID = (string)forumItem.Element("id"),
                       Name = (string)forumItem.Element("name"),
                       URL = (string)forumItem.Element("url"),
                       Description = (string)forumItem.Element("description"),
                       Type = (string)forumItem.Element("type"),
                       TopicCount = (string)forumItem.Element("topics"),
                       ReplyCount = (string)forumItem.Element("replies"),
                       LastPost = lastPost,
                       IsRedirect = !string.IsNullOrEmpty(lastPost)
                   }).ToList();