Linq2XML用于添加到数组的语法

时间:2013-10-10 18:59:14

标签: c# linq

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

工作代码:

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

我的班级架构 - FYI

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

任何代码段/指针都会提供帮助

2 个答案:

答案 0 :(得分: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..
  }

答案 1 :(得分: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