我正在自学C#,希望有人能指出我做错了什么。我尝试在获得匹配项时遍历一些XML数据并创建对象。
我的活动顺序是
在第4步中使用填充列表创建了我的对象,但是在第2步中重复时,该对象随后被覆盖。
class XMLData {
public static List<Device> Search(XElement XE)
{
//local variables
bool DeviceCreated = false;
List<Device> Devices = new List<Device>();
string Out = "";
List<int> List1 = new List<int>();
List<int> List2 = new List<int>();
List<int> List3 = new List<int>();
IEnumerable<XElement> Logic =
from LL in XE.Descendants("Text")
select LL;
foreach (XElement XML in Logic)
{
//Regex Patterns
string pattern1 = @"(?=O\()[^\)]+(?<=S)";
string pattern2 = @"(?=O\()[^\)]+(?<=I)";
string pattern3 = @"(?=O\()[^\)]+(?<=FA)";
string pattern4 = @"(?=X\()[^\)]+(?<=F)";
string pattern5 = @"(?=O\()[^\)]+(?<=L)";
string pattern6 = @"(?=O\()[^\)]+(?<=FT).+?(?<=)";
MatchCollection All = Common.Find(XML);
if (Regex.Match(XML.Value, pattern1).Success)
{
//Clear down data ready to create a new device
DeviceCreated = false;
List1.Clear();
List2.Clear();
List3.Clear();
List1 = Common.Find(All);
}
else if (Regex.Match(XML.Value, pattern2).Success)
{
List2 = Common.Find(All);
}
else if (Regex.Match(XML.Value, pattern3).Success)
{
List3 = Common.Find(All);
}
else if (Regex.Match(XML.Value, pattern5).Success)
{
// create a device when we see this pattern as we should now have all of the data in the lists
if (!DeviceCreated)
{
Devices.Add(new Device(List1, List2, List3));
DeviceCreated = true;
}
}
else
{
//nothing
}
}
return Devices;
}
}
答案 0 :(得分:2)
当您执行List1 = Common.Find(All)
,List2 = Common.Find(All)
等操作时,它只会覆盖现有列表。
执行附加操作,或以C#的方式编写AddRange()
:
List1.AddRange(Common.Find(All));