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

后端 未结 14 2059
梦如初夏
梦如初夏 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:58

    Not sure how elegant this is, but here you go.

    Since ICollection<> doesn't give you indexing I just used IEnumerable<>, and since I didn't need the index on the IList<> I used IEnumerable<> there too.

    public static IEnumerable IndexedLookup(
        IEnumerable indexes, IEnumerable items)
    {
        using (var indexesEnum = indexes.GetEnumerator())
        using (var itemsEnum = items.GetEnumerator())
        {
            int currentIndex = -1;
            while (indexesEnum.MoveNext())
            {
                while (currentIndex != indexesEnum.Current)
                {
                    if (!itemsEnum.MoveNext())
                        yield break;
                    currentIndex++;
                }
    
                yield return itemsEnum.Current;
            }
        }
    }
    

    EDIT: Just noticed my solution is similar to Erics.

提交回复
热议问题