如何检查项目是否已在列表框中

如何检查项目是否已在列表框中

问题描述:

说我有这样定义的视图模型

Say I have a view model defined this way

public class DataVM
{
    public int number { get; set; }
    public string name { get; set; }
}

然后在我的代码中的某个地方,我要填充DataListbox:

Then somewhere in my code I want to do this to populate DataListbox:

List<DataVM> data = new List<DataVM>();

for (int i = 0; i < data.Count; i++)
{
    if (DataListbox.Items.Contains(data[i]))
    {
        //do nothing
    }
    else
    {
        DataListbox.Add(data[i]);
    }
}

但是,即使该项目已经在DataListbox中,该行if (DataListbox.Items.Contains(data[i]))始终评估为false,并且应评估为true.我不明白为什么它不起作用.

However, this line if (DataListbox.Items.Contains(data[i])) always evaluate to false even when that item is already in DataListbox and it should evaluate to true. I don't get why it doesn't work.

我在这里做错什么以及如何解决?

What am I doing wrong here and how do I fix it?

代码始终评估为false的原因是,.NET框架在检查是否相等时默认情况下会比较指向内存的指针,而不是变量内容两个对象. 因此,与其使用内置的Contains函数,不如遍历列表框的所有元素,并通过比较唯一属性来检查 ,如果该项已添加到列表框中:

The reason why your code always evaluates false is because the .NET framework compares the pointers to the memory and not the variables content by default when using checking for equality of two objects. So instead of using the built in Contains function you should iterate through all elements of the listbox and check by comparing an unique property if the item was already added to the listbox:

您将必须执行以下操作(使用LINQ;使用唯一属性替换数据[i].名称和项目.):

You would have to do something like this (using LINQ; Replace data[i].name and item.Value with the unique property):

bool listContainsItem = DataListbox.Items.Any(item => item.Value == data[i].name);

或使用旧"编码样式:

for (int i = 0; i < data.Count; i++)
{
   bool itemAlreadyAdded = false;
   foreach (var item in DataListbox.Items)
   {
       if (item.Value == data[i].name)
       {
            itemAlreadyAdded = true;
            break;
       }
   }
   if (itemAlreadyAdded)
   {
        //do nothing
    }
    else
    {
        DataListbox.Add(data[i]);
    }
}