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

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

    Several good suggestions here already, I'll just throw in my two cents.

    int counter = 0;
    var x = collection
        .Where((item, index) => 
            counter < indices.Length && 
            index == indices[counter] && 
            ++counter != 0);
    

    edit: yah, didn't think it through the first time around. the increment has to happen only when the other two conditions are satisfied..

    0 讨论(0)
  • 2020-12-13 05:38

    Here's a faster version:

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 05:40

    You could do it in an extension method:

    static IEnumerable<T> Extract<T>(this ICollection<T> collection, IList<int> indexes)
    {
       int index = 0;
       foreach(var item in collection)
       {
         if (indexes.Contains(index))
           yield item;
         index++;
       }
    }
    
    0 讨论(0)
  • 2020-12-13 05:48
        public static IEnumerable<T> WhereIndexes<T>(this IEnumerable<T> collection, IEnumerable<int> indexes)
        {
            IList<T> l = new List<T>(collection);
            foreach (var index in indexes)
            {
                yield return l[index]; 
            }
        }
    
    0 讨论(0)
  • 2020-12-13 05:49

    Maybe I'm missing something, but what's wrong with just:

    indexes.Select( (index => values[index]))
    
    0 讨论(0)
  • 2020-12-13 05:50

    I would use an extension Method

    public static IEnumerable<T> Filter<T>(this IEnumerable<T> pSeq, 
                                           params int [] pIndexes)
    {
          return pSeq.Where((pArg, pId) => pIndexes.Contains(pId));
    }
    
    0 讨论(0)
提交回复
热议问题