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
.
You can just iterate over it, check the ID and return the index of the object. int index = -1; for(int i=0;i<PLUList. Count;i++) { PLU plu = PLUList[i]; if (plu.ID == yourId) { index = i; break; } } if (index > -1) { // Do something here } else { // Do sth else here.. }
The true difference is rather straightforward:ObservableCollection implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList implements IBindingList.
An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated.
Although this post is old and already answered, it can still be helpful to others so I here is my answer.
You can create extension methods similar to List<T>.FindIndex(...)
methods:
public static class ObservableCollectionExtensions
{
public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
{
return ts.FindIndex(0, ts.Count, match);
}
public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
{
return ts.FindIndex(startIndex, ts.Count, match);
}
public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
{
if (startIndex < 0) startIndex = 0;
if (count > ts.Count) count = ts.Count;
for (int i = startIndex; i < count; i++)
{
if (match(ts[i])) return i;
}
return -1;
}
}
Usage:
int index = PLUList.FindIndex(x => x.ID == 13);
if (index > -1)
{
// Do something here...
}
else
{
// Do something else here...
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With