How to search an item and get its index in Observable Collection
Use LINQ :-)
var q = PLUList.Where(X => X.ID == 13).FirstOrDefault();
if(q != null)
{
// do stuff
}
else
{
// do other stuff
}
Use this, if you want to keep it a struct:
var q = PLUList.IndexOf( PLUList.Where(X => X.ID == 13).FirstOrDefault() );
if(q > -1)
{
// do stuff
}
else
{
// do other stuff
}
If you want to retrieve the item from your list, just use LINQ:
PLU item = PLUList.Where(z => z.ID == 12).FirstOrDefault();
But this will return the item itself, not its index. Why do you want the index?
Also, you should use class
instead of struct
if possible. Then you could test item
against null
to see if the ID
was found in the collection.
if (item != null)
{
// Then the item was found
}
else
{
// No item found !
}
Here is a quick fix.
int findID = 3;
int foundID= -1;
for (int i = 0; i< PLUList.Count; i++)
{
if (PLUList[i].ID == findID)
{
foundID = i;
break;
}
}
// Your code.
if (foundID > -1) {
// Do something here
...