简体   繁体   中英

Collect indexes from list

Is there a linq function in c# which enables you to collect IEnumerables from a specific range of indexes?

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.

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> ). In the more general case of having an IEnumerable or ICollection , you wouldn't be able to index directly. 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.

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.

If you've got an IEnumerable<T> instead, you can use the Where overload which provides the index as well as the value. So:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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