How to search an item and get its index in Observable Collection

user995387 picture user995387 · Feb 17, 2012 · Viewed 51.1k times · Source
public struct PLU
{ 
    public int ID { get; set; } 
    public string name { get; set; } 
    public double price { get; set; } 
    public int quantity {get;set;}
}

public static ObservableCollection<PLU> PLUList = new ObservableCollection<PLU>();

I have the ObservableCollection as above. Now I want to search the ID in the PLUList and get its index like this:

int index = PLUList.indexOf();
if (index > -1)
{
    // Do something here
}
else
{
    // Do sth else here..
}

What's the quick fix?

EDIT:

Let's assume that some items were added to PLUList and I want to add another new item. But before adding I want to check if the ID already exists in the list. If it does then I would like to add +1 to the quantity.

Answer

Mithrandir picture Mithrandir · Feb 17, 2012

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
}