C# XML 到 LINQ 多个同名元素,如何让它们保存在同一个对象中
我有以下代码:
_logs.AddRange(elements
.Select(log => new Log()
{
tid = (log.Element("tid") == null) ? "" : log.Element("tid").Value,
zid = (log.Element("zid") == null) ? "" : log.Element("zid").Value,
create = (log.Element("create") == null) ? "" : log.Element("create").Value,
data = (log.Element("data") == null) ? null : log.Elements("data")
.Select(x => new Data()
{
data = (log.Element("data") == null) ? "" : log.Element("data").Value
}).ToList()
}));
数据元素在每个对象中出现多次。为什么当它读取这些对象时,它显示 x 具有正确的数据,但当我查看 _logs 时,它只显示第一个值。
例如,如果数据如下所示:
<data>1</data>
<data>2</data>
<data>3</data>
那么数据列表将显示 [0] = 1 , [1] = 1 , [2] = 1
谢谢
I have the following codE:
_logs.AddRange(elements
.Select(log => new Log()
{
tid = (log.Element("tid") == null) ? "" : log.Element("tid").Value,
zid = (log.Element("zid") == null) ? "" : log.Element("zid").Value,
create = (log.Element("create") == null) ? "" : log.Element("create").Value,
data = (log.Element("data") == null) ? null : log.Elements("data")
.Select(x => new Data()
{
data = (log.Element("data") == null) ? "" : log.Element("data").Value
}).ToList()
}));
The data element shows up multiple times in each object. Why when it reads through these objects does it show x having the correct data but then when I look at _logs it shows only the first value.
For example if data looked like this:
<data>1</data>
<data>2</data>
<data>3</data>
So then the data list would show [0] = 1 , [1] = 1 , [2] = 1
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
Select()
已关闭,您当前只是选择第一个项目的值,而是执行以下操作:此外,您也不需要初始
null
检查 -如果没有数据元素,它将只是一个包含零项的枚举,因此这将起作用:Your
Select()
is off, you are currently just selecting the value of the first item all over, instead do this:Also you don't need the initial
null
check - if there is no data element it will just be an enumeration with zero items, so this will work: