gpt4 book ai didi

c# - 使用双 Foreach 循环输出数据时结果相同

转载 作者:太空宇宙 更新时间:2023-11-03 21:49:11 25 4
gpt4 key购买 nike

我需要将一个字符串设置成这样

<Student>
<StudentID></StudentID>
<FirstName></FirstName>
<Fees>
<Fee>
<FeeID></FeeID>
</Fee>
</Fees>
</Student>
<Student>
<StudentID></StudentID>
<FirstName></FirstName>
<Fees>
<Fee>
<FeeID></FeeID>
</Fee>
</Fees>
</Student>
... and so on

我的代码

string strFeeData = ""; // XML Content for Fees
string strStuData = ""; // XML Content for Students with Fees

foreach (var studentData in sorted)
{
foreach(Fee feeData in studentData.Fees)
{
strFeeData = strFeeData + "<Fee>\n\t<FeeID>" + feeData.FeeID + "</FeeID>\n\t<FeeName>" + feeData.FeeName + "</FeeName>\n\t<Amount>" + feeData.Amount + "</Amount>\n\t<DueDate>" + feeData.DueDate + "</DueDate>\n</Fee>\n";
}
strStuData = strStuData + "<Student>\n\t<StudentID>" + studentData.StudentID + "</StudentID>\n<FirstName>" + studentData.FirstName + "</FirstName>\n<LastName>" + studentData.LastName + "</LastName>\n<Grade>" + studentData.Grade + "</Grade>\n<Fees>\n\t" + strFeeData + "</Fees></Student>\n";
}

我正确输出了这部分

<Student>
<StudentID>1</StudentID>
<FirstName>David</FirstName>
...
<Student>
<StudentID>2</StudentID>
<FirstName>John</FirstName>

但要收费

<Fees>
<Fee>
<FeeID>12</FeeID>
....
<Fees>
<Fee>
<FeeID>12</FeeID>

我为每个学生收取相同的费用。

我的双 foreach 循环有什么问题?

(我已经检查过sorted的Fee有不同的值,问题一定出在双foreach循环)

谢谢

最佳答案

在外循环中用空字符串初始化strFeeData:

foreach (var studentData in sorted)
{
strFeeData = "";

foreach(Fee feeData in studentData.Fees)
{
strFeeData = strFeeData + "<Fee>\n\t<FeeID>" + feeData.FeeID + "</FeeID>\n\t<FeeName>" + feeData.FeeName + "</FeeName>\n\t<Amount>" + feeData.Amount + "</Amount>\n\t<DueDate>" + feeData.DueDate + "</DueDate>\n</Fee>\n";
}
strStuData = strStuData + "<Student>\n\t<StudentID>" + studentData.StudentID + "</StudentID>\n<FirstName>" + studentData.FirstName + "</FirstName>\n<LastName>" + studentData.LastName + "</LastName>\n<Grade>" + studentData.Grade + "</Grade>\n<Fees>\n\t" + strFeeData + "</Fees></Student>\n";
}

但是,使用字符串连接创建 XML 确实是个坏主意!您应该阅读有关序列化或 LINQ to XML 的内容!

LINQ to XML 版本

var xml = sorted.Select(s => new XElement("Student"
new XElement("StudentID", s.StudentID),
new XElement("FirstName", s.FirstName),
new XElement("LastName", s.LastName),
new XElement("Fees",
s.Fees.Select(f => new XElement("Fee",
new XElement("FeeID", f.FeeID))).ToArray())));

关于c# - 使用双 Foreach 循环输出数据时结果相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15379810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com