什么是最优雅的方式通过指数从集合获得一组项目? [英] What is the most elegant way to get a set of items by index from a collection?

查看:151
本文介绍了什么是最优雅的方式通过指数从集合获得一组项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于

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

什么是最优雅的方式来提取所有的 T 基础上,提供的索引的指标

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

例如,如果包含

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

指标包含

1, 3

返回的是

"Cleveland," "Glenn"

编辑:假设指标总是排序上升。

推荐答案

这是假设该索引序列非负指数的单调递增序列。该战略很简单:每个索引,撞了一个枚举的集合点,并产生元素

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)在额外的存储空间 - 这些解决方案是O(n)的空间

  • O(n)的时间 - 这些解决方案是二次型的时间

  • 适用于任何两个序列;不需要的ICollection或IList的。

  • 只有一次迭代的收集;一些解决方案遍历集合多次(建立一个清单出来,例如。)

缺点:


  • 难读

这篇关于什么是最优雅的方式通过指数从集合获得一组项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆