gpt4 book ai didi

c# - 任意数量对象的笛卡尔积

转载 作者:行者123 更新时间:2023-11-30 17:30:27 27 4
gpt4 key购买 nike

<分区>

我希望在 C# 中获取任意数量对象的笛卡尔积。我的情况有点不寻常——我的输入不是基本类型列表,而是具有基本类型列表属性的对象。

我的输入输出对象如下:

public class Input
{
public string Label;
public List<int> Ids;
}

public class Result
{
public string Label;
public int Id;
}

一些示例输入数据:

var inputs = new List<Input>
{
new Input { Label = "List1", Ids = new List<int>{ 1, 2 } },
new Input { Label = "List2", Ids = new List<int>{ 2, 3 } },
new Input { Label = "List3", Ids = new List<int>{ 4 } }
};

我期望的输出对象:

var expectedResult = new List<List<Result>>
{
new List<Result>
{
new Result{Label = "List1", Id = 1},
new Result{Label = "List2", Id = 2},
new Result{Label = "List3", Id = 4}
},
new List<Result>
{
new Result{Label = "List1", Id = 1},
new Result{Label = "List2", Id = 3},
new Result{Label = "List3", Id = 4}
},
new List<Result>
{
new Result{Label = "List1", Id = 2},
new Result{Label = "List2", Id = 2},
new Result{Label = "List3", Id = 4}
},
new List<Result>
{
new Result{Label = "List1", Id = 2},
new Result{Label = "List2", Id = 3},
new Result{Label = "List3", Id = 4}
}
};

如果我事先知道“输入”中的项目数量,我可以这样做:

var knownInputResult = 
from id1 in inputs[0].Ids
from id2 in inputs[1].Ids
from id3 in inputs[2].Ids
select
new List<Result>
{
new Result { Id = id1, Label = inputs[0].Label },
new Result { Id = id2, Label = inputs[1].Label },
new Result { Id = id3, Label = inputs[2].Label },
};

我正在努力使它适应任意数量的输入 - 有没有可能的方法来做到这一点?

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