我想生成一个由字符串列表(实际上是对象列表,但为简单起见,我们将使用字符串)的所有可能组合的列表。我需要这个列表以便在单元测试中测试每个可能的组合。
例如,如果我有以下列表:
var allValues = new List<string>() { "A1", "A2", "A3", "B1", "B2", "C1" }
我需要一个 List<List<string>>
,其中包含所有组合,如:
A1
A2
A3
B1
B2
C1
A1 A2
A1 A2 A3
A1 A2 A3 B1
A1 A2 A3 B1 B2
A1 A2 A3 B1 B2 C1
A1 A3
A1 A3 B1
etc...
使用递归函数可能是获取所有组合的方法,但它似乎比我想象的要困难。
有什么提示吗?
谢谢。
编辑:两种解决方案,使用或不使用递归:
public class CombinationGenerator<T>
{
public IEnumerable<List<T>> ProduceWithRecursion(List<T> allValues)
{
for (var i = 0; i < (1 << allValues.Count); i++)
{
yield return ConstructSetFromBits(i).Select(n => allValues[n]).ToList();
}
}
private IEnumerable<int> ConstructSetFromBits(int i)
{
var n = 0;
for (; i != 0; i /= 2)
{
if ((i & 1) != 0) yield return n;
n++;
}
}
public List<List<T>> ProduceWithoutRecursion(List<T> allValues)
{
var collection = new List<List<T>>();
for (int counter = 0; counter < (1 << allValues.Count); ++counter)
{
List<T> combination = new List<T>();
for (int i = 0; i < allValues.Count; ++i)
{
if ((counter & (1 << i)) == 0)
combination.Add(allValues[i]);
}
// do something with combination
collection.Add(combination);
}
return collection;
}
}