C# 在 ObservableCollection 中查找索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10618351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding an index in an ObservableCollection
提问by user101010101
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.
此集合已填充,其中包含许多 ProcessModel。
My question is that I have an ProcessModel, which I want to find in my _collection.
我的问题是我有一个 ProcessModel,我想在我的 _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.
我想这样做,所以我能够找到 ProcessModel 在 _collection 中的位置的索引,我真的不确定如何做到这一点。
I want to do this because I want to get at the ProcessModel N+1 ahead of it in the ObservableCollection (_collection).
我想这样做是因为我想在 ObservableCollection (_collection) 中提前获得 ProcessModel N+1。
采纳答案by daryal
var x = _collection[(_collection.IndexOf(ProcessItem) + 1)];
回答by Kendall Frey
http://msdn.microsoft.com/en-us/library/ms132410.aspx
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
}
回答by Nikhil Agrawal
Since ObservableCollectionis a sequence, hence we can use LINQ
由于ObservableCollection是一个序列,因此我们可以使用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.
我已经将您的索引增加到 1,它符合您的要求。
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");

