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

查看:102
本文介绍了创建一个列表,从每个嵌套列表中获取一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是先前帖子中的后续问题.在澄清了我之前的问题后,建议我发表新帖子,因为问题已经发生了巨大变化,这是一个很好的建议.这是原始问题:为什么LINQ Select表达式不起作用

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

我正在寻找将oldList转换为newList的方法.面临的挑战是我不知道将有多少个嵌套列表或每个列表中将有多少个项目.您可以假定每个嵌套列表的长度都完全相同.有任何想法吗?感谢您的帮助.

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.

这是代码:

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

这篇关于创建一个列表,从每个嵌套列表中获取一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆