Faking IGrouping for LINQ

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?

+3
source share
3 answers

Inspired by David B. 's answer , I came up with a simple solution. It is so simple that I have no idea how I missed it.

To do the filtering, I obviously need to know what value of the condition I am filtering. Therefore, given the condition,, cI can simply project the filtered list as:

filteredList.GroupBy(x => c)

( x).

, , , , . , , , .

+2

, -...

:

public class CustomGroup<T, U>
{
  T Key {get;set;}
  IEnumerable<U> GroupMembers {get;set} 
}

:

var result = customGroups
  .SelectMany(cg => cg.GroupMembers, (cg, z) => new {Key = cg.Key, Value = z})
  .GroupBy(x => x.Key, x => x.Value)
+3

How to add the result to LookUpand use it for the remaining time?

var lookup = data.ToLookUp(i => Foo(i));
0
source

Source: https://habr.com/ru/post/1712148/


All Articles