从foreach循环和IF语句不需要的输出 [英] Undesired output from foreach loop and IF statement
本文介绍了从foreach循环和IF语句不需要的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有从foreach循环格式化输出的问题。我应该怎么做来格式化输出,显示下面的code?我目前使用以下code:
I am having a problem with formatting the output from foreach loop. What should I do to format output as showed below the code? I am currently using following code:
foreach (AddEntry list in addedEntry)
{
// Displaying and formating the output in text box in MainWindow.
mainWindow.ChangeTextBox += list.Type + Environment.NewLine;
if (cmbType.SelectedIndex == 1)
mainWindow.ChangeTextBox += "URL: " + list.URL + Environment.NewLine;
if (cmbType.SelectedIndex == 2)
mainWindow.ChangeTextBox += "Software Name: " + list.SoftwareName + Environment.NewLine;
if (cmbType.SelectedIndex == 2)
mainWindow.ChangeTextBox += "Serial Code: " + list.SerialCode + Environment.NewLine;
if (cmbType.SelectedIndex == 0 || cmbType.SelectedIndex == 1)
mainWindow.ChangeTextBox += "User Name: " + list.UserName + Environment.NewLine;
if (cmbType.SelectedIndex == 0 || cmbType.SelectedIndex == 1)
mainWindow.ChangeTextBox += "Password: " + list.Password + Environment.NewLine;
mainWindow.ChangeTextBox += Environment.NewLine;
}
首页输出:
PC Password
User Name: a
Password: b
然后添加一个条目...
Then adding another entry...
第二输出:
PC Password
URL: e // this should not be here
User Name: a
Password: b
Web Site Password
URL: www.
User Name: www
Password: www
第二输出应该是:
PC Password
User Name: a
Password: b
Web Site Password
URL: www.
User Name: www
Password: www
希望一些技巧。
问候。
推荐答案
添加显示类型= cmdType.SelectedIndex到的AddEntry
Add DisplayType = cmdType.SelectedIndex to the AddEntry
使用字符串构建器试过吗?
Tried using a String Builder?
StringBuilder sb = new StringBuilder(mainWindow.ChangeTextBox);
foreach (AddEntry list in addedEntry)
{
sb.AppendLine(list.Type);
if (list.DisplayType == 1)
sb.AppendLine("URL: " + list.URL);
if (list.DisplayType == 0 || list.DisplayType == 1) {
sb.AppendLine("User Name: " + list.UserName);
sb.AppendLine("Password: " + list.Password);
}
if (list.DisplayType == 2) {
sb.AppendLine("Software Name: " + list.SoftwareName);
sb.AppendLine("Serial Code: " + list.SerialCode);
sb.AppendLine("Software Name: " + list.SoftwareName);
}
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
注意临时变量
这篇关于从foreach循环和IF语句不需要的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文