Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

c# - What is the most elegant way to get a set of items by index from a collection?

Given

IList<int> indexes;
ICollection<T> collection;

What is the most elegant way to extract all T in collection based on the the indexes provided in indexes?

For example, if collection contained

"Brian", "Cleveland", "Joe", "Glenn", "Mort"

And indexes contained

1, 3

The return would be

"Cleveland," "Glenn"

Edit: Assume that indexes is always sorted ascending.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This assumes that the index sequence is a monotone ascending sequence of non-negative indices. The strategy is straightforward: for each index, bump up an enumerator on the collection to that point and yield the element.

public static IEnumerable<T> GetIndexedItems<T>(this IEnumerable<T> collection, IEnumerable<int> indices)
{
    int currentIndex = -1;
    using (var collectionEnum = collection.GetEnumerator())
    {
        foreach(int index in indices)
        {
            while (collectionEnum.MoveNext()) 
            {
                currentIndex += 1;
                if (currentIndex == index)
                {
                    yield return collectionEnum.Current;
                    break;
                }
            }
        }    
    }
}

Advantages of this solution over other solutions posted:

  • O(1) in extra storage -- some of these solutions are O(n) in space
  • O(n) in time -- some of these solutions are quadradic in time
  • works on any two sequences; does not require ICollection or IList.
  • only iterates the collection once; some solutions iterate the collection multiple times (to build a list out of it, for instance.)

Disadvantages:

  • harder to read

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...