Creating a list, getting an element from each nested list

痴心易碎 提交于 2019-12-11 12:40:14

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/37791100/creating-a-list-getting-an-element-from-each-nested-list

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