foreach 循环和 IF 语句的不需要的输出 [英] Undesired output from foreach loop and IF statement

查看:49
本文介绍了foreach 循环和 IF 语句的不需要的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在格式化 foreach 循环的输出时遇到问题.我应该怎么做才能格式化输出,如下面的代码所示?我目前正在使用以下代码:

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

希望得到一些提示.

问候.

推荐答案

Add DisplayType = 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆