特定
IList<int> indexes;
ICollection<T> collection;
Run Code Online (Sandbox Code Playgroud)
什么是最优雅的方式来提取所有牛逼在收集基础上,提供的索引的索引?
例如,如果包含集合
"Brian", "Cleveland", "Joe", "Glenn", "Mort"
Run Code Online (Sandbox Code Playgroud)
并包含索引
1, 3
Run Code Online (Sandbox Code Playgroud)
回报将是
"Cleveland," "Glenn"
Run Code Online (Sandbox Code Playgroud)
编辑:假设索引始终按升序排序.
Eri*_*ert 24
这假设索引序列是非负指数的单调递增序列.策略很简单:对于每个索引,将集合上的枚举器提升到该点并生成元素.
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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
此解决方案优于其他解决方案:
缺点:
这是一个更快的版本:
IEnumerable<T> ByIndices<T>(ICollection<T> data, IList<int> indices)
{
int current = 0;
foreach(var datum in data.Select((x, i) => new { Value = x, Index = i }))
{
if(datum.Index == indices[current])
{
yield return datum.Value;
if(++current == indices.Count)
yield break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1828 次 |
最近记录: |