【问题标题】:Finding an index in an ObservableCollection在 ObservableCollection 中查找索引
【发布时间】:2012-05-16 12:17:51
【问题描述】:

这可能很简单,但我无法提出解决方案。

我有一个:

ObservableCollection<ProcessModel> _collection = new ObservableCollection<ProcessModel>();

这个集合被填充,包含许多 ProcessModel。

我的问题是我有一个 ProcessModel,我想在我的 _collection 中找到它。

我想这样做,以便能够在 _collection 中找到 ProcessModel 所在位置的索引,但我真的不确定该怎么做。

我想这样做是因为我想在 ObservableCollection (_collection) 中获得 ProcessModel N+1 的前面。

【问题讨论】:

    标签: c# .net observablecollection


    【解决方案1】:
    var x = _collection[(_collection.IndexOf(ProcessItem) + 1)];
    

    【讨论】:

    • 谢谢。有没有一种使用 linq 检查 null 的好方法?说 + 1 的索引何时超出范围。
    • @user101010101:检查i+1 值。它不应大于 ObservableCollection 的长度/计数。
    • @Nikhil 抱歉,我是新手,你是怎么做到的?
    • 这是如何获取索引的?这将获取索引处的项目,下面的答案获取索引。
    • @jdmdevdotnet 嗯? IndexOf 返回索引。
    【解决方案2】:

    http://msdn.microsoft.com/en-us/library/ms132410.aspx

    用途:

    _collection.IndexOf(_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】:

      由于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);
      

      我已经将您的索引增加到符合您要求的 1。

      ProcessModel pm = _collection[_collection.IndexOf(mydesiredProcessModel) + 1];
      

      ProcessModel pm = _collection.ElementAt(_collection.IndexOf(mydesiredProcessModel) + 1);
      

      编辑不为空

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 2022-11-22
        • 2011-12-30
        • 1970-01-01
        • 2014-08-27
        相关资源
        最近更新 更多