Enumerate through a subset of a Collection in C#?

后端 未结 6 1474
粉色の甜心
粉色の甜心 2021-02-08 01:12

Is there a good way to enumerate through only a subset of a Collection in C#? That is, I have a collection of a large number of objects (say, 1000), but I\'d like to enumerate

6条回答
  •  攒了一身酷
    2021-02-08 01:37

    Adapting Jarad's code once again, this extention method will get you a subset that is defined by item, not index.

        //! Get subset of collection between \a start and \a end, inclusive
        //! Usage
        //! \code
        //! using ExtensionMethods;
        //! ...
        //! var subset = MyList.GetRange(firstItem, secondItem);
        //! \endcode
    class ExtensionMethods
    {
        public static IEnumerable GetRange(this IEnumerable source, T start, T end)
        {
    #if DEBUG
            if (source.ToList().IndexOf(start) > source.ToList().IndexOf(end))
                throw new ArgumentException("Start must be earlier in the enumerable than end, or both must be the same");
    #endif
            yield return start;
    
            if (start.Equals(end))
                yield break;                                                    //start == end, so we are finished here
    
            using (var e = source.GetEnumerator())
            { 
                while (e.MoveNext() && !e.Current.Equals(start));               //skip until start                
                while (!e.Current.Equals(end) && e.MoveNext())                  //return items between start and end
                    yield return e.Current;
            }
        }
    }
    

提交回复
热议问题