尝试比较两个列表视图并输出到 c# 中的新列表视图

Trying to compare two listviews and output into a new listview in c#

所以我正在尝试比较两个列表视图,其中包含安装前的服务和安装后的服务 - 我尝试使用以下方法来做到这一点

serviceinfo si = new serviceinfo();
        for (int i = 0; i < listView2.Items.Count; i++)
        {
            string testing = listView1.Items[i].Text;
            //MessageBox.Show(testing);
            ListViewItem item = listView2.FindItemWithText(testing);
            //MessageBox.Show(item.ToString());
            if (item == null)
            { 
                //MessageBox.Show("Test");
                si.name = item.Text;
                listView3.Items.Add(si.name);
            }
            else
            {
                //MessageBox.Show("Item exists");
            }
        }

如果我将 "item == null" 更改为“!=”,这会输出所有相同的项目 - 但是当它是“==”时,我会得到一个 "Object not referenced error",据我所知,它指的是尝试设置 si.name 到空对象但是我需要文本。

如有任何帮助,我们将不胜感激。

可能你需要使用这样的东西。代码中的注释解释了逻辑。

// Loop over the items in the first list....
for (int i = 0; i < listView1.Items.Count; i++)
{
    // Get the text of the item at i pos in the first listview
    string testing = listView1.Items[i].Text;

    // Search it in the second listview
    ListViewItem item = listView2.FindItemWithText(testing);

    // If not found...
    if (item == null)
    { 
        // Add the text to the third listview
        listView3.Items.Add(testing);
    }
    else
    {
        MessageBox.Show("Item exists");
    }
}

注意:我想你想知道最新安装是否添加了一些新服务,在这种情况下,上面的代码假定第一个 ListView 是服务列表AFTER 安装,第二个 ListView 包含 BEFORE 安装服务。

如果不是这种情况,则只需反转 ListView 变量名称..... (不过我建议你给这个对象起一个更容易理解的名字,比如 lvBeforeInstall、lvAfterInstall、lvAddedServices)

首先,您可以添加 如果(listView1.Items.Count < i)return; 到你的子程序的顶部。这将避免空引用。 我强烈建议比较模型中的数据而不是视图中的数据。值得花时间研究 MVVM 或 MVC 架构,以及如何在当代编程设计模式中处理这个问题。