我有3个列表,其中包含字符串
GenderList = ["M", "F"]
AgeList = ["10-15", "16-20", "21-26"]
CityList = ["CityA", "CityB"]
我想在列表上做叉积,但是很麻烦:
如果用户要求gender_city
:
我需要以下条件:
foreach(var g in GenderList)
foreach(var c in CityList
.....
如果用户要求输入gender_city_age
,则循环必须为:
foreach(var g in GenderList)
foreach(var c in CityList)
foreach(var a in AgeList)
....
如果用户要求city_age
foreach(var c in CityList)
foreach(var a in AgeList)
...
我该怎么做?我有大约20
个列表,我需要动态地乘以列表中的项目
谢谢
答案 0 :(得分:4)
让我们从广义的Cartesian
开始:
private static IEnumerable<T[]> Cartesian<T>(IEnumerable<IEnumerable<T>> source) {
T[][] lists = source
.Select(line => line.ToArray())
.ToArray();
if (source.Any(line => !line.Any()))
yield break;
int[] indexes = new int[lists.Length];
do {
yield return lists.Select((line, index) => line[indexes[index]]).ToArray();
for (int i = 0; i < indexes.Length; ++i)
if (++indexes[i] < lists[i].Length)
break;
else
indexes[i] = 0;
}
while (!indexes.All(index => index == 0));
}
然后我们可以尝试使用它。让我们将要查询的所有集合组织到一个 dictionary 中:
// we allow to use any IEnumerable<string>, not necessary List<string>
Dictionary<string, IEnumerable<string>> data =
new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase) {
{ "Gender", new [] { "M", "F" } },
{ "Age", new List<string> { "10-15", "16-20", "21-26" } },
{ "City", new [] { "CityA", "CityB" } },
};
并查询它:
string userChoice = "gender_city_age";
var result = Cartesian(userChoice.Split('_').Select(name => data[name]));
// Have a look at the result:
string report = string.Join(Environment.NewLine, result
.Select(line => string.Join(", ", line)));
Console.Write(report);
结果:
M, CityA, 10-15
F, CityA, 10-15
M, CityB, 10-15
F, CityB, 10-15
M, CityA, 16-20
F, CityA, 16-20
M, CityB, 16-20
F, CityB, 16-20
M, CityA, 21-26
F, CityA, 21-26
M, CityB, 21-26
F, CityB, 21-26