c# - LINQ 到 XML : result based on attributes

标签 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];

提前致谢

最佳答案

只设置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
}

关于c# - LINQ 到 XML : result based on attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39246817/

相关文章:

c# - 正确处理单例 IDisposable 对象

c# - 从数据库查询 DateTime 字段时,我可以控制 DateTimeKind 吗?

arrays - 在数组的数组中查找元素的索引

java - 如何用stax恢复属性

java - 解释 XMLBeans 如何处理 '-' 字符

java - 使用 ant 根据 jar 属性编辑文件

c# - 为什么 foreach(var i in array2D) 适用于多维数组?

c# - 从对象中拆箱值类型

javascript - ES6 中的扩展运算符在旧版 JavaScript 中转换成什么?它比 array.concat 更 coSTLier 吗?

javascript - 是否有 ES6 快捷方式来比较元素数组和对象键并删除不匹配的元素?