问题
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