gpt4 book ai didi

c# - 列表上的动态 for 循环 (C#)

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:54 25 4
gpt4 key购买 nike

我有 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 个列表,我需要动态乘以列表的项目谢谢

最佳答案

让我们从广义笛卡尔开始:

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

然后我们就可以尝试使用它了。让我们将要查询的所有集合组织到一个字典中:

// 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

关于c# - 列表上的动态 for 循环 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55397239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com