Is there a way to reference the source enumerable inside a method running on that same enumerable?
For example, this code repeats the original enumerable range of 1-6:
IEnumerable<int> result = Enumerable.Range(1, 6)
.Where(a => Enumerable.Range(1, 6).Count() % 2 == 0);
I want to know if there is a cleaner way to produce it with repeating the original enumerable, such as:
IEnumerable<int> result = Enumerable.Range(1, 6)
.Where(a => [source reference].Count() % 2 == 0);
Yes, I know the following is a solution… But is there a way to do a direct reference to an in-memory enumerable, as demonstrated above?
IEnumerable<int> source = Enumerable.Range(1, 6);
IEnumerable<int> result = source.Where(a => source.Count() % 2 == 0);
I’m not looking for a specific answer to the lines of code above; they are just an example demonstrating what I want to know.
None of the built-in
IEnumerableextension methods can do what you want. They all accept lamba expressions that only operate on the individual items, so your expressions have no access to the parent container.Nothing is stopping you from rolling your own, though, something like:
Personally, I think your original solution is much clearer, more maintainable, and better than crafting your own custom extension method, but it’s certainly possible.