本文介绍了获取C#中的键值对列表的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的键值对:
I have a key value pair like this:
var accounts = new List<KeyValuePair<int,int>>();
,帐户内容如下:
{[4,10000]}
{[4,19000]}
{[4,11000]}
{[4,12000]}
{[4,13036]}
{[4,47100]}
{[5,19300]}
{[5,32900]}
{[5,95800]}
{[6,95800]}
如何获得accounts
中的键值对的所有可能的组合,使得我拥有:
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
推荐答案
经过短暂搜索,我发现您可以使用 CartesianProduct扩展方法,来自埃里克·利珀特的博客:
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();
正在执行的操作:
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}));
}
这篇关于获取C#中的键值对列表的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!