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

### 问题描述

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

## 推荐答案

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

### 问题描述

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.

## 推荐答案

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