Question

I have a key value pair like this:

var accounts = new List<KeyValuePair<int,int>>();

and the contents of accounts looks like this:

{[4,10000]}
{[4,19000]}
{[4,11000]}
{[4,12000]}
{[4,13036]}
{[4,47100]}
{[5,19300]}
{[5,32900]}
{[5,95800]}
{[6,95800]}

How can I get all possible combinations of the key value pairs in accounts such that I have:

[{4,10000},{5,19300},{6,95800}],
[{4,10000},{5,32900},{6,95800}].....

The data structure containing the final result is not of much importance to me, I'm just interested in achieving this as efficiently as possible

Was it helpful?

Solution

after a short search i found that you can do it using the CartesianProduct Extension Method from Eric Lippert's Blog:

var result = list.GroupBy(t => t.Key).CartesianProduct();

as it is doing:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
  this IEnumerable<IEnumerable<T>> sequences) 
{ 
  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
  return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) => 
      from accseq in accumulator 
      from item in sequence 
      select accseq.Concat(new[] {item})); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top