gpt4 book ai didi

c# - 错误 : A query body must end with a select clause or a group clause

转载 作者:数据小太阳 更新时间:2023-10-29 02:57:53 29 4
gpt4 key购买 nike

我有这样一个 xml:

<countries>
<country ID="MX">
<idea ID="Valor1">nota1</idea>
<idea ID="Valor2">nota2</idea>
<idea ID="Valor3">nota3</idea>
<idea ID="Valor4">nota4</idea>
</country>
<country ID="US">
<idea ID="Valor1">nota1</idea>
<idea ID="Valor2">nota2</idea>
<idea ID="Valor3">nota3</idea>
<idea ID="Valor4">nota4</idea>
</country>
</countries>

如何使用 LINQ to XML 获取特定类型的列表?我试过这样的事情:

我创建了一个类:

public class Ideas
{
public string Country { get; set; }

public List<ListItem> ListIdeas { get; set; }
}

然后我用这个类做一个列表:

XDocument xdoc = XDocument.Load(this.Server.MapPath("~/config/ideas.xml"));

var cat = from p in xdoc.Descendants("countries")
.Elements("country")
.Select(m => new Ideas
{
Country = m.Attribute("ID").Value,
ListIdeas = m.Elements("idea")
.Select(c =>
new ListItem
{
Text = c.Attribute("ID").Value ,
Value = c.Value
}).ToList()
});

但是我得到下一个错误:

A query body must end with a select clause or a group clause

The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

最佳答案

您混合了查询语法和扩展方法语法。选择一个

var r = (from c in xdoc.Element("countries")
.Elements("country")
select new Country
{
ID = c.Attribute("ID").Value,
Ideas = (from i in c.Elements("idea")
select new Idea
{
Text = i.Attribute("ID").Value,
Value = i.Value
}).ToList()
}).ToList();

请注意,为了更好的可读性,我重命名了您的类和属性。


在另一种语法中相同:

var q = xdoc.Element("countries")
.Elements("country")
.Select(c => new Country
{
ID = c.Attribute("ID").Value,
Ideas = c.Elements("idea")
.Select(i => new Idea
{
Text = i.Attribute("ID").Value,
Value = i.Value
})
.ToList()
})
.ToList();

关于c# - 错误 : A query body must end with a select clause or a group clause,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487410/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com