我有一个类似这样的 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/