简体   繁体   English

从列表中收集索引

[英]Collect indexes from list

Is there a linq function in c# which enables you to collect IEnumerables from a specific range of indexes? c#中是否有linq函数,使您可以从特定范围的索引中收集IEnumerables?

An example would be 一个例子是

        var objectArray = new string[] { "Bill", "Bob", "Joe", "Phil", "Tom", "Paul" };
        var indexArray = new int[] { 1, 3, 5 };

        var list = objectArray.Where(SOME_FUNCTION_TO_GET_INDEXES ??).ToList();

        //output would be list:
        //Bob
        //Phil
        //Paul

Just use Select with your indexArray and return the item from objectArray via indexing. 只需将SelectindexArray一起使用,并通过索引从objectArray返回该项目。

var list = indexArray.Select(i => objectArray[i]);

Note that this works very efficiently for any collection that allows indexing (for example, Array and List<T> ). 请注意,这对于任何允许建立索引的集合(例如ArrayList<T> )都非常有效。 In the more general case of having an IEnumerable or ICollection , you wouldn't be able to index directly. 在具有IEnumerableICollection的更一般的情况下,您将无法直接建立索引。 In which case you'd need to see Jon's answer. 在这种情况下,您需要查看乔恩的答案。 Depending on the sizes of the lists involved, and how many items you need to look up, it might be worth converting your IEnumerable to an Array or List (using ToArray for example) first. 根据所涉及列表的大小以及需要查找的项目数量,可能首先需要将IEnumerable转换为ArrayList (例如,使用ToArray )。

If the original datasource is already accessible by index, such as for a list or an array, you can just use indexArray.Select as Matt showed. 如果原始数据源已经可以通过索引访问,例如列表或数组,则可以使用Matt所示的indexArray.Select

If you've got an IEnumerable<T> instead, you can use the Where overload which provides the index as well as the value. 如果有IEnumerable<T> ,则可以使用Where重载,它提供索引和值。 So: 所以:

var list = objectArray.Where((value, index) => indexArray.Contains(index))
                      .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM