Imagine that you have a large dataset that may or may not be filtered by the specific state of the elements in the dataset that can be computationally intensive. In the case when it is not filtered, the elements are grouped by the value of this condition - the condition is calculated once.
However, in the case when the filtering has been carried out, although the following code is still expecting to see the collection IEnumerable<IGrouping<TKey, TElement>>, it makes no sense to perform an operation GroupBythat will cause the condition to be repeated - it is evaluated a second time for each element. Instead, I would like to be able to create IEnumerable<IGrouping<TKey, TElement>>by appropriately wrapping the filtered results and thus avoid another state assessment.
Besides implementing my own class that provides an interface IGrouping, is there any other way to implement this optimization? Are there any existing LINQ methods to support this, which will give me the result IEnumerable<IGrouping<TKey, TElement>>? Is there any other way that I have not considered?
source
share