Reputation: 54
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
Upvotes: 0
Views: 97
Reputation: 45155
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.
Upvotes: 9
Reputation: 1503974
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();
Upvotes: 8