Only3lue Only3lue - 13 days ago 9
C# Question

C# ObservableCollection.IndexOf(...) retrurns -1

I made this code to check a Collection for same Objects with same Value, but it returns the index -1 and causes an IndexOutOfRangeException.

List<MyFileInfo> selectedItemsList = dataInbox.SelectedItems.Cast<MyFileInfo>().ToList();
foreach (MyFileInfo file in selectedItemsList)
{
if (!file.AdditionalColumn.Equals(""))
{
inDB = new ZeichnungInDB(file.FileInfo.Name, file.AdditionalColumn, file.AdditionalColumn2, file.FileInfo.Extension,
txtAenderungExtern.Text, file.AdditionalColumn3,
int.Parse(txtProjectNumber.Text), txtTag.Text, bemerkung, anhangPfad, cmbDokumententyp.Text, false);
if (zeichnungCollection.Count > 0)
{
if (zeichnungCollection[zeichnungCollection.IndexOf(inDB)].Zeichnungsnummer != inDB.Zeichnungsnummer &&
zeichnungCollection[zeichnungCollection.IndexOf(inDB)].Extension != inDB.Extension)
{
zeichnungCollection.Add(inDB);
}
else
{
sameData = true;
}
}
else
{
zeichnungCollection.Add(inDB);
}
}
}


Has someone an idea for my problem?

Btw: How can I format the code I´m posting here? Because in Visual Studio it looks different like here, there is no Tab in after the first line.

Answer

You are creating a new instance of an object, you are then attempting to find the Index of that object where your collection actually holds reference to a different instance.

You can use FindIndex to pass in a predicate and find the index of the object where a condition is true. https://msdn.microsoft.com/en-us/library/x1xzf2ca(v=vs.110).aspx

Alternatively, you could use FirstOrDefault with some null checking https://msdn.microsoft.com/en-us/library/bb340482(v=vs.110).aspx