C# 用于添加到数组的Linq2XML语法
我实际上有一个工作代码,但我想学习另一种方法来得到相同的答案,我被卡住了 工作代码:C# 用于添加到数组的Linq2XML语法,c#,linq,C#,Linq,我实际上有一个工作代码,但我想学习另一种方法来得到相同的答案,我被卡住了 工作代码: var responseElement = XElement.Load("QuoteResponse.xml"); var myobject = new QuoteResponse { response = new Response { id = (string)responseElement.Attribute("id"), quotes = new Quotes
var responseElement = XElement.Load("QuoteResponse.xml");
var myobject = new QuoteResponse
{
response = new Response
{
id = (string)responseElement.Attribute("id"),
quotes = new Quotes
{
quote = (
from o in responseElement.Elements("quotes").Elements("quote")
select new Quote
{
ask = (string)o.Element("ask")
}).ToArray()
}
}
};
替代解决方案(我被最后一块卡住了-向Quote[]添加新的Quote对象
var responseElement = XElement.Load("QuoteResponse.xml");
var quoteElement = responseElement.Element("quote");
var myobject = new QuoteResponse
{
response = new QR.Response
{
id = (string)responseElement.Attribute("id"),
quotes = new Quotes
{
quote = new Quote[]
{
//Need to do something here so I can basically
//add each instance of new Quote to the array
new Quote
{
...
}
}
}
}
};
我的类模式-仅供参考
public class QuoteResponse
{
public Response response { get; set; }
}
public class Response
{
public string @id { get; set; }
public Quotes quotes { get; set; }
}
public class Quotes
{
public Quote[] quote { get; set; }
}
public class Quote
{
public string ask { get; set; }
}
任何代码片段/指针都会非常有用我认为您正在寻找带有对象初始化的集合初始化
var allQuotes = responseElement.Elements("quotes").Elements("quote").ToArray();
quotes = new Quotes[]
{
new Quote
{
ask = (string)allQuotes[0].Element("ask")
},
new Quote
{
ask = (string)allQuotes[1].Element("ask")
},
new Quote
{
ask = (string)allQuotes[2].Element("ask")
}, ...
// happy guessing what the last index will be..
}
也许是这样的:
quote = new Quote[]
{
new Quote {
ask = "something"
},
new Quote {
ask = "something else"
}
}
但是你不能在未知数量的quote元素中使用它。最好和最优雅的方法是使用你的工作版本
你应该考虑的一件事是把你的公共财产的情况变成这样。
public class QuoteResponse
{
public Response Response { get; set; }
}
public class Response
{
public string Id { get; set; }
public IEnumerable<Quote> Quotes { get; set; }
}
// Let's get rid of this class altogether, use IEnumerable<Quote> instead
public class Quotes
{
public Quote[] Quote { get; set; }
}
public class Quote
{
public string Ask { get; set; }
}
公共类引用响应
{
公共响应{get;set;}
}
公众课堂反应
{
公共字符串Id{get;set;}
公共IEnumerable引号{get;set;}
}
//让我们完全去掉这个类,改用IEnumerable
公共类引用
{
公共引号[]引号{get;set;}
}
公开课报价
{
公共字符串Ask{get;set;}
}
当然,你可以自由地使用任何你想要的格式。但是,你目前的格式正在损害大多数C#开发者:)
阅读Microsoft的建议:
下面是关于
IEnumerable
的事情:为什么不使用工作代码呢?这需要硬编码引号的数量。King-我正在使用工作代码,但在某个地方看到了第二种方法,并想尝试用不同的语法执行相同的操作。CSharpie-hmm intresting-显然不想这样做硬代码-这意味着我只有一个选项(工作代码1),您确定这一行:quote=newquote[]
接受您作为答案。感谢或者稍微不那么脆弱:var quotes=allQuotes.Select(q=>newquote{ask=q.Element(“ask”).Value})代码>米凯尔-你的反馈真的很有帮助。始终接受改进代码的建议(无论代码多么小)。非常感谢你。我也投了一票