创建列表,从每个嵌套列表中获取一个元素[英] Creating a list, getting an element from each nested list

本文是小编为大家收集整理的关于创建列表,从每个嵌套列表中获取一个元素的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

这是早期帖子的关注问题.在澄清了我之前的问题之后,建议我发表新的帖子,因为这个问题发生了巨大变化,这是一个很好的建议.这是最初的问题:为什么这个linq select linq select select select expression

更新的问题如下.我想要的是获取所有置换,每个列表中的每个新组仅由一个列表列表中的一个元素组成.例如:

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

我正在寻找某种方式将Oldlist转换为新清单.面临的挑战是,我不知道会有多少个嵌套列表或每个列表中有多少个项目.您可以假设每个嵌套列表的长度完全相同.有任何想法吗?感谢您的帮助.

推荐答案

您可以阅读有关 this Eric Lippert关于使用Linq的笛卡尔产品的文章.

这个想法是访问每个列表,以当前的笛卡尔产品集为该列表的笛卡尔产品.

这是代码:

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

用法:

var newList = CartesianProduct(oldList);

本文地址:https://www.itbaoku.cn/post/1557033.html

问题描述

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.

推荐答案

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