C# LINQ到xml:基于属性的结果
我有一个与此类似的XMLC# LINQ到xml:基于属性的结果,c#,arrays,xml,linq,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>30
<?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>
我想根据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();
您也可以这样做:(然后在开始时加载它,每次都使用它)
我根据飞机模型的座位数量创建一个字典
,然后您可以使用它来创建您的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
}
你好,吉拉德,非常感谢你的帮助,目前我在手机上,我将在我的电脑上尝试你的解决方案。干杯,伙计!早上好,您的解决方案看起来很不错,但数组在函数中不可见。它表示“seats”名称在当前上下文中不存在。第二种方法呢?我还没试过这本字典,因为我不懂怎么用,我还在用谷歌搜索。您每次使用它的意思是什么?@user3136729-请参阅更新,了解如何将p用于其他函数。我建议阅读更多关于静态的内容,以及何时使用它。关于字典,你可以有一个局部变量来存储它,然后每次你需要座位的时候,你都可以寻址它,而不是再次访问文件并从中读取it@user3136729-关于
p
的错误,我建议在使用linq和读取文件等之前,更多地学习过程编程和oop编程
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"]];
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
}