给定
IList<int> indexes;
ICollection<T> collection;
根据索引中提供的索引,提取集合中的所有 T 的最优雅方法是什么?
例如,如果包含集合
"Brian", "Cleveland", "Joe", "Glenn", "Mort"
并包含索引
1, 3
返回将是
"Cleveland," "Glenn"
编辑:假设索引始终按升序排序。
最佳答案
这假定索引序列是非负索引的单调递增序列。该策略很简单:对于每个索引,将集合上的枚举数增加到该点并产生元素。
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;
}
}
}
}
}
该解决方案相对于其他已发布解决方案的优势:
额外存储中的
缺点:
关于c# - 从集合中按索引获取一组项目的最优雅方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1018407/