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

后端 未结 14 2053
梦如初夏
梦如初夏 2020-12-13 04:57

Given

IList indexes;
ICollection collection;

What is the most elegant way to extract all T in

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 05:38

    Here's a faster version:

    IEnumerable ByIndices(ICollection data, IList 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;
            }
        }
    }
    

提交回复
热议问题