Finding an index in an ObservableCollection

流过昼夜 提交于 2019-12-12 17:40:51

问题


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).


回答1:


var x = _collection[(_collection.IndexOf(ProcessItem) + 1)];



回答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
}



回答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");


来源:https://stackoverflow.com/questions/10618351/finding-an-index-in-an-observablecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!