I recently encounter a couple of cases where it makes me wonder if there is any way to get internal index, or if not, to generate index efficiently when using LINQ.
Consider the following case:
List<int> list = new List() { 7, 4, 5, 1, 7, 8 };
In C#, if we are to return the indexes of "7" on the above array using LINQ, we cannot simply using IndexOf/LastIndexOf - for it will only return the first/last result.
This will not work:
var result = list.Where(x => x == 7).Select(y => list.IndexOf(y));
We have several workarounds for doing it, however.
For instance, one way of doing it could be this (which I typically do):
int index = 0;
var result = from x in list
let indexNow = index++
where x == 7
select indexNow;
It will introduce additional parameter indexNow by using let.
And also another way:
var result = Enumerable.Range(0, list.Count).Where(x => list.ElementAt(x) == 7);
It will generate another set of items by using Enumerable.Range and pick the result from it.
Now, I am wondering if there is any alternative, simpler way of doing it, such as:
- if there is any (built-in) way to get the internal index of the IEnumerable without declaring something with let or
- to generate the index for the IEnumerable using something other than Enumerable.Range (perhaps something like new? Which I am not too familiar how to do it), or
- anything else which could shorten the code but still getting the indexes of the IEnumerable.