0

我实际上有一个工作代码,但想学习另一种方法来获得相同的答案并被卡住

工作代码:

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; }
}

任何代码片段/指针都会有帮助

4

2 回答 2

1

我认为您正在寻找带有对象初始化的集合初始化。

可能是这样的:

quote = new Quote[]
{
    new Quote {        
        ask = "something"
    },
    new Quote {        
        ask = "something else"
    }
}

但是您不能将其与未知数量的引用元素一起使用。最好和最优雅的方法是使用您的工作版本。

但是,您应该考虑的一件事是将您的公共属性的情况改为这种情况。

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; }
}

当然,您可以自由使用您想要的任何格式。但是使用您当前的格式,您正在积极伤害大多数 C# 开发人员:)

阅读微软的建议:http: //msdn.microsoft.com/en-us/library/ms229012.aspx

这是关于IEnumerable<T>事情的:http: //msdn.microsoft.com/en-us/library/9eekhta0.aspx

于 2013-10-10T19:20:08.010 回答
1
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..
  }
于 2013-10-10T19:11:33.287 回答