Say I have a view model defined this way
public class DataVM
{
public int number { get; set; }
public string name { get; set; }
}
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]);
}
}
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?
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:
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);
Or by using "old" coding style:
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]);
}
}