首页 > 解决方案 > 比较C#中列表中的项目

问题描述

我想将组合框的选定项与其他组合框的选定项进行比较,为此我已经在列表中注册了所有组合框并将其命名为“panel1kilist”,现在我面临的问题是,当两个组合框中有相同的项目时,首先是消息框显示“找不到匹配项”,然后显示“找到匹配项”实际上它首先进入内部循环的 else 语句,然后进入 if 语句,请帮助

    private void button1_Click(object sender, EventArgs e)
        {
            bool check = false;
            bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
            try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
            {
                for (int i = 1; i < panel1kilist.Count; i++)
                {
                    for (int j = i + 1; j < panel1kilist.Count; j++)
                    {
                        if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
                        {
                            if (check == false)
                            {
                                MessageBox.Show("match found");
                            }
                            check = true;
                        }

                        else
                        {
                            if (check1 == false)
                            {
                                MessageBox.Show("no match found");
                            }
                            check1 = true;
                        }
                    }
                }
            }
            catch (System.NullReferenceException)
            {
                MessageBox.Show("please fill all the boxes first");
            }


        }

标签: c#listcombobox

解决方案


你的问题不是很清楚,但我仍然试图给你一些帮助。如评论中所述,您的代码中有几个小问题:

1.外部for循环

for (int i = 1; i < panel1kilist.Count; i++)

您定义 i = 1,这意味着您跳过 panel1kilist 中的第一项,因为列表和数组从索引 0 开始

2.使用你的布尔变量

if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
     if (check == false)
     {
          MessageBox.Show("match found");
     }
     check = true;
}
else
{
     if (check1 == false)
     {
          MessageBox.Show("no match found");
     }
     check1 = true;
}

在开始 for 循环之前定义 bool 变量。因此,每当您将变量 check 和 check1 设置为 true 时,if 条件 check == false 和 check1 == false 将永远不会返回 true。因此,除了第一个“找到匹配”和“未找到匹配”之外,您永远不会收到任何消息。

3. 我提出的解决方案

使用 foreach 循环并在找到匹配项后中断循环,在循环仅显示消息之后。代码:

var matchFound = false;

foreach (var combobox in panel1kilist)
{
     foreach (var comboboxToMatch in panel1kilist.Skip(1))
     {
          if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
          {
               matchFound = true;
               // Stops the inner loop in case of a match
               break;
          }
     }

     // Stops the outer loop in case of a match
     if(matchFound)
     {
          break;
     }
}

if(matchFound)
{
     MessageBox.Show("match found");
}

推荐阅读