Creating a list, getting an element from each nest

2019-08-15 06:44发布

This is a follow question from an earlier post. After clarifying my earlier question, it was recommended that I make a new post as the question had shifted dramatically, which was a good suggestion. Here is the original question: Why doesn't this LINQ Select expression work

The updated question is as follows. What I want is to get every permutation whereby each new group is made of only one element from a list of lists. As an example:

List<List<int>> oldList = {{1,2},{3,4}};
List<List<int>> newList = {{1,3},{1,4},{2,3},{2,4}};

I'm looking for some way to convert oldList into newList. The challenge is that I don't know how many nested lists there will be or how many items will be in each list. You can assume each nested list is the exact same length. Any ideas? Thanks for any help.

标签: c# linq set
1条回答
家丑人穷心不美
2楼-- · 2019-08-15 07:11

You can read about this post of Eric Lippert about computing a Cartesian product with LINQ.

The idea is visit each list making a cartesian product of that list with the current cartesian product set.

This is the code:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(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 }));
}

Usage:

var newList = CartesianProduct(oldList);
查看更多
登录 后发表回答