foreach 没有很好地阅读 .descendants 并转到 else 语句之前如果



我仍在学习C#

我目前正在开发一个过滤系统,并有一个if语句列表,该列表阻止用户执行任何操作。现在,每当用户提交ID时,我的foreach都应该遍历已经提交的ID的列表,检查它们是否已经存在。

错误在于,当用户提交一个已经存在的ID时,它在第一次运行中不会看到现有的ID,因此它将创建并填充一个节点,但在第二次运行中,它会发送一条错误消息&中断会话。

我的代码:

private async void btnAddId_Click(object sender, RoutedEventArgs e)
{
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(xmldoc);
XmlNode NodeEl = Xdoc.SelectSingleNode("root/filter/filter_item");
XmlNode NodeList = Xdoc.SelectSingleNode("root/filter");
var root = XDocument.Load(xmldoc).Root;
var filter = root.Element("filter");
int parsedValue;
foreach (var f in filter.Descendants())
{
if (f.Value == tbAddId.Text)
{
MessageBox.Show("Value already exists in the orderlist!");
}
else if (!int.TryParse(tbAddId.Text, out parsedValue))
{
MessageBox.Show("Input isn't numeric!");
}
else if (tbAddId.Text == "")
{
MessageBox.Show("No value was given!");
}
else if (tbAddId.Text == "Add ID")
{
MessageBox.Show("No value was given!");
}
else if (NodeList.InnerText == "")
{
NodeEl.InnerText = tbAddId.Text;
tbAddId.Text = "Add ID";
tbAddId.Foreground = Brushes.Gray;
await api.config_Load();
await api.Page_Load();
}
else
{
XmlNode filterItem = Xdoc.CreateElement("filter_item");
NodeList.AppendChild(filterItem);
filterItem.InnerText = tbAddId.Text;
}
tbOrderDisplay.Text += f.Value + " ";
}         
Xdoc.Save(xmldoc);
}

XML内容

<?xml version="1.0"?>
<root>
<bol_client_id></bol_client_id>
<!--- this is the client id-->
<bol_client_secret></bol_client_secret>
<!-- this is the client secret -->
<customer_id></customer_id>
<company_phone></company_phone>
<auth_token_url></auth_token_url>
<bol_orders_url></bol_orders_url>
<debug_mode>true</debug_mode>
<filter>
<filter_item>1172828940</filter_item>
<filter_item>1173700637</filter_item>
</filter>
</root>

在尝试插入值之前检查是否存在:

private async void btnAddId_Click(object sender, RoutedEventArgs e)
{
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(xmldoc);
XmlNode NodeEl = Xdoc.SelectSingleNode("root/filter/filter_item");
XmlNode NodeList = Xdoc.SelectSingleNode("root/filter");
var root = XDocument.Load(xmldoc).Root;
var filter = root.Element("filter");
int parsedValue;
//1. Check for duplicates
foreach (var f in filter.Descendants())
{
if (f.Value == tbAddId.Text)
{
MessageBox.Show("Value already exists in the orderlist!");
tbOrderDisplay.Text += f.Value + " ";
return;
}
}
//2. Validate and insert
if (!int.TryParse(tbAddId.Text, out parsedValue))
{
MessageBox.Show("Input isn't numeric!");
}
else if (tbAddId.Text == "")
{
MessageBox.Show("No value was given!");
}
else if (tbAddId.Text == "Add ID")
{
MessageBox.Show("No value was given!");
}
else if (NodeList.InnerText == "")
{
NodeEl.InnerText = tbAddId.Text;
tbAddId.Text = "Add ID";
tbAddId.Foreground = Brushes.Gray;
await api.config_Load();
await api.Page_Load();
}
else
{
XmlNode filterItem = Xdoc.CreateElement("filter_item");
NodeList.AppendChild(filterItem);
filterItem.InnerText = tbAddId.Text;
}
Xdoc.Save(xmldoc);
}

最新更新