C# 在LINQ查询中填充对象数组
如何在C# 在LINQ查询中填充对象数组,c#,asp.net,asp.net-mvc,linq,C#,Asp.net,Asp.net Mvc,Linq,如何在LINQ查询中填充对象数组 这是我的数据模型 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
LINQ查询中填充对象数组
这是我的数据模型
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>
.....
.....
.....
.....
.....
.....
.....
.....
.....
.....
.....
.....
您只需在查询内部进行另一个查询。例如,如果频道
元素包含项目
元素,则可以执行以下操作:
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
提供xml文件格式。@AhmadAbbasi实际上我指的是item元素的格式。但这没关系,请参阅我的更新,如果元素名称错误,您可以更改它。至少您现在必须有一个想法:)