LINQ to xml:基于属性的结果

时间:2016-08-31 10:15:12

标签: c# arrays xml linq

我有一个与此类似的XML

<?xml version="1.0" encoding="UTF-8"?>
<schedule>

<Aircraft mdy="Thursday, September 1, 2016" Destination="London"  
  Source="Greece" ID="B747">
 <FROM>GRE</FROM>
 <TO>LON</TO>
 <Miles>3000</Miles>
 </Aircraft>

 <Aircraft mdy="Thursday, September 1, 2016" Destination="New York"  
  Source="Greece" ID="B747">
  <FROM>GRE</FROM>
  <TO>IT</TO>
  <Miles>20000</Miles>
  </Aircraft>

 <Aircraft mdy="Thursday, September 1, 2016" Destination="Mykonos"  
  Source="Athens" ID="A320">
  <FROM>ATH</FROM>
  <TO>MYK</TO>
  <Miles>300</Miles>
  </Aircraft>

  </schedule>

请帮我解决以下问题。我的LINQ经验有限且处于新手级别。

var p = from a in reservation.Descendants("Aircrafts")
        where a.Attribute("ID").Value.Equals("B747")
        ...
        change array contents

我想根据ID属性动态更改下面数组的内容。例如,如果ID ==“B747”就座[100],否则如果ID ==“A320”就座[200]等。

static int p= 100;
public static bool[] seats;
seats = new bool[p];

提前致谢

1 个答案:

答案 0 :(得分:1)

只需设置p即可:

var p = (from element in XDocument.Load("data.xml").Descendants("Aircraft")
         let type = element.Attribute("ID").Value
         where type.Equals("B747")
         select type == "B747" ? 100 :
                type == "A320" ? 200 : 0).FirstOrDefault();

您也可以这样做:(然后在开头加载它并每次都使用它)

var seatsForModel = (from element in reservation.Descendants("Aircraft")
                     let type = element.Attribute("ID").Value
                     select new
                     {
                        AircraftModel = type,
                        Seats = type == "B747" ? 100 :
                                type == "A320" ? 200 : 0
                     }).Distinct().ToDictionary(key => key.AircraftModel, value => value.Seats);

// Output: [B747, 100],
//         [A320, 200]

bool[] seatsTaken = new bool[seatsForModel["B747"]];

我根据它拥有的座位数创建Dictionary<string,int>飞机模型,然后您可以使用它来创建bool[]

虽然......我更好的设计会在模型和座位数之间建立映射,然后将其加入xml中的项目

至于无法访问另一个函数中的p,请在函数中包装linq并从另一个函数调用它:

public int GetNumberOfSeats(string aircraftModel)
{
    var p = (from element in XDocument.Load("data.xml").Descendants("Aircraft")
             let type = element.Attribute("ID").Value
             where type.Equals(aircraftModel)
             select type == "B747" ? 100 :
                    type == "A320" ? 200 : 0).FirstOrDefault();
    return p;
}

public void assignFirstClass()
{
    var p = GetNumberOfSeats("B747");
    bool[] seats = new bool[p];

    //Rest of code
}