Finding an index in an ObservableCollection
23,292
Solution 1
var x = _collection[(_collection.IndexOf(ProcessItem) + 1)];
Solution 2
http://msdn.microsoft.com/en-us/library/ms132410.aspx
Use:
_collection.IndexOf(_item)
Here is some code to get the next item:
int nextIndex = _collection.IndexOf(_item) + 1;
if (nextIndex == 0)
{
// not found, you may want to handle this as a special case.
}
else if (nextIndex < _collection.Count)
{
_next = _collection[nextIndex];
}
else
{
// that was the last one
}
Solution 3
Since ObservableCollection
is a sequence, hence we can use LINQ
int index =
_collection.Select((x,i) => object.Equals(x, mydesiredProcessModel)? i + 1 : -1)
.Where(x => x != -1).FirstOrDefault();
ProcessModel pm = _collection.ElementAt(index);
I already incremented your index to 1 where it matches your requirement.
OR
ProcessModel pm = _collection[_collection.IndexOf(mydesiredProcessModel) + 1];
OR
ProcessModel pm = _collection.ElementAt(_collection.IndexOf(mydesiredProcessModel) + 1);
EDIT for Not Null
int i = _collection.IndexOf(ProcessItem) + 1;
var x;
if (i <= _collection.Count - 1) // Index start from 0 to LengthofCollection - 1
x = _collection[i];
else
MessageBox.Show("Item does not exist");
Author by
user101010101
Updated on June 18, 2020Comments
-
user101010101 about 4 years
This may be very simple but I have not been able to come up with a solution.
I am have a:
ObservableCollection<ProcessModel> _collection = new ObservableCollection<ProcessModel>();
This collection is populated, with many ProcessModel's.
My question is that I have an ProcessModel, which I want to find in my _collection.
I want to do this so I am able to find the index of where the ProcessModel was in the _collection, I am really unsure how to do this.
I want to do this because I want to get at the ProcessModel N+1 ahead of it in the ObservableCollection (_collection).