Getting all possible combinations of a List of KeyValue Pairs in C#

我们两清 提交于 2021-02-05 06:39:45

问题


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


回答1:


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})); 
}


来源:https://stackoverflow.com/questions/19075173/getting-all-possible-combinations-of-a-list-of-keyvalue-pairs-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!