【问题标题】:Fill object array inside of LINQ Query在 LINQ Query 中填充对象数组
【发布时间】:2014-02-07 00:03:09
【问题描述】:

如何在LINQ Query 中填写Object Array

这是我的数据模型

public class Test
    {
        public string Link { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public Item[] Items { get; set; }
    }

 public class Item
    {
        public string Title { get; set; }
        public string Link { get; set; }
        public string Guid { get; set; }
        public DateTime PublishDate { get; set; }
        public string Description { get; set; }
    }

这里是查询

var data = from feed in feedXml.Descendants("channel")
                        select new Rss
                        {
                            Title = feed.Element("title").Value,
                            Link = feed.Element("link").Value,
                            Description = feed.Element("description").Value,
                            Items = // here i have to fill the array of items
                        };

更新 xml 格式

<channel>
  .....  
  <item>.....</item>
  <item>.....</item>
  <item>.....</item>
</channel>
<channel>
  .....  
  <item>.....</item>
  <item>.....</item>
  <item>.....</item>
</channel>
<channel>
  .....  
  <item>.....</item>
  <item>.....</item>
  <item>.....</item>
</channel>

【问题讨论】:

  • 提供您的 xml 文件格式。

标签: c# asp.net asp.net-mvc linq


【解决方案1】:

您只需要在查询中进行另一个查询。例如,如果channel 元素包含item 元素,那么您可以这样做:

Items = feed.Elements("item")
           .Select(x => new Item { // set property values })
           .ToArray()

更新:您似乎正在阅读 RSS 文件,因此您的查询应该是这样的:

var data = from feed in feedXml.Descendants("channel")
            select new Rss
            {
                Title = (string) feed.Element("title"),
                Link = (string) feed.Element("link"),
                Description = (string) feed.Element("description"),
                Items = feed.Elements("item")
                    .Select(
                        x =>
                            new Item
                            {
                                Title = (string) x.Element("title"),
                                Link = (string) x.Element("link"),
                                Description = (string) x.Element("description"),
                                Guid = (string) x.Element("guid"),
                                PublishDate = (DateTime) x.Element("pubDate")
                            })
                    .ToArray()

            };

我还使用了显式转换而不是尝试直接访问Value 属性来防止NullReferenceException

【讨论】:

  • @AhmadAbbasi 实际上我的意思是项目元素的格式。不过没关系,看看我的更新,如果元素名称错误你可以更改它。至少你现在必须有一个想法:)
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 2022-01-24
  • 2016-01-19
  • 2022-08-02
  • 2013-03-10
  • 2021-08-16
  • 2013-06-30
相关资源
最近更新 更多