gpt4 book ai didi

c# - 从集合中按索引获取一组项目的最优雅方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 08:50:26 24 4
gpt4 key购买 nike

给定

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

根据indexes中提供的索引提取collection中所有T的最优雅的方法是什么?

例如,如果集合包含

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

和包含的索引

1, 3

返回的是

"Cleveland," "Glenn"

编辑:假设 indexes 总是升序排列。

最佳答案

这假设索引序列是非负索引的单调升序序列。该策略很简单:对于每个索引,将集合中的枚举数增加到该点并生成元素。

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;
}
}
}
}
}

此解决方案相对于已发布的其他解决方案的优势:

  • O(1) 的额外存储——这些解决方案中的一些是 O(n) 的空间
  • 时间复杂度为 O(n) -- 这些解决方案中的一些在时间上是二次的
  • 适用于任意两个序列;不需要 ICollection 或 IList。
  • 只迭代集合一次;一些解决方案多次迭代集合(例如,从中构建一个列表。)

缺点:

  • 更难阅读

关于c# - 从集合中按索引获取一组项目的最优雅方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1018407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com