当返回单个实体时,Linq to XML查询有效,但需要为list< T> [英] Linq to XML query works when returning single entity but needs to be of list<T>
本文介绍了当返回单个实体时,Linq to XML查询有效,但需要为list< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出此XML:
<foo>
<xxx>Some XXX</xxx>
<bar Attr1="true">Some Bar</bar>
<bar Attr2="true">Some Bar #2</bar>
<bar>Some Bar #3</bar>
<bar>Some Bar #4</bar>
</foo>
我有这个LINQ查询:
I have this LINQ query:
var foos = from query in xmlData.Descendants("foo")
from bars in query.Elements("bar")
select new FooClass
{
xxx = (string)query.Element("xxx"),
barCollection = new BarClass
{
display = bars.Value,
attr1Exists = (answers.Attribute("Attr1") != null ? true : false)
attr2Exists = (answers.Attribute("Attr2") != null ? true : false)
}
};
如果将barCollection定义为BarClass,这将非常有用.
This works great if barCollection is defined as BarClass.
但是我需要它成为List< BarClass>.
However I need it to be List<BarClass>.
我尝试了其他方法,并且在bar是List< string>的情况下可以使用此方法:
I've tried other approaches, and got this to work if bar is a List<string>:
var foos = from query in xmlData.Descendants("foo")
select new FooClass
{
xxx = (string)query.Element("xxx"),
bar = query.Elements("bar").Select(x => x.Value).ToList()
};
但是我找不到混合两者的方法.
But I can't find a way to mix the two.
有人可以展示如何结合这两种解决方案,以便将BarCollection填充为用户定义的类型,即List< BarClass>吗?
Can someone show how to combine the two solutions so that BarCollection is populated as a user defined type, namely List<BarClass>?
更新:下面的最终工作代码,使用提供的解决方案
var foos = from query in xmlData.Descendants("foo")
select new FooClass
{
xxx = (string)query.Element("xxx"),
bar = query.Elements("bar").Select(x => new BarClass
{
display = x.Value,
attr1Exists = x("Attr1") != null ? true : false),
attr2Exists = x("Attr2") != null ? true : false)
}
).ToList()
};
推荐答案
将.Select(x => x.Value)
更改为.Select(x => new BarClass(...))
.
这篇关于当返回单个实体时,Linq to XML查询有效,但需要为list< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文