【发布时间】:2016-11-12 08:44:16
【问题描述】:
所以我一直在努力寻找一种方法来创建所有组合,而不会从包含自定义对象的多个列表中重复。当然,还有一些额外的限制使它更具挑战性。
基本上,我正在从包含零件信息的 .csv 文件中解析一堆数据。然后将此数据传递给自定义对象,然后将这些对象添加到基于其“组”的列表中。 (见下面的代码)
因此,一旦信息被解析,我现在就有 6 个列表,其中包含任意数量的元素。现在我需要按照以下规则生成这 6 个列表之间的所有组合:
- A 组中的一个对象
- B 组中的两个对象(不重复)
- C 组中的三个对象(不重复)
- groupD 中的一个对象
- E 组中的一个对象
- groupF 中的一个对象
这些对象随后用于创建 ModuleFull 对象,我的总体最终结果应该是包含从部件列表生成的所有组合的List<ModuleFull>。
虽然我没有使用自定义对象列表对其进行测试,但我能够找到一种使用 LINQ 的方法,因为我意识到我的列表都包含不同数量的元素。
因此,如果我想出一种使用递归解决此问题的方法,我将不胜感激。
下面是解析数据的代码:
using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
Part tempPart = new Part(fields[0], fields[2], fields[1], double.parse(fields[4]), long.parse(fields[3]));
allParts.Add(tempPart);
if (tempPart.group == "A")
{
aParts.Add(tempPart);
}
else if (tempPart.group == "B")
{
bParts.Add(tempPart);
}
else if (tempPart.group == "C")
{
cParts.Add(tempPart);
}
else if (tempPart.group == "D")
{
dParts.Add(tempPart);
}
else if (tempPart.group == "E")
{
eParts.Add(tempPart);
}
else if (tempPart.group == "F")
{
fParts.Add(tempPart);
}
}
以下是填充列表的对象的两个类:
public class Part
{
public string idNum; //0 locations when being parsed
public string name; //2
public string group; //1
public double tolerance; //4
public long cost; //3
public Part(string id, string nm, string grp, double tol, long cst)
{
idNum = id;
name = nm;
group = grp;
tolerance = tol;
cost = cst;
}
}
public class ModuleFull
{
public Part groupA;
public Part groupBOne;
public Part groupBTwo;
public Part groupCOne;
public Part groupCTwo;
public Part groupCThree;
public Part groupD;
public Part groupE;
public Part groupF;
public ModuleFull(Part a, Part b1, Part b2, Part c1, Part c2, Part c3, Part d, Part e, Part f)
{
groupA = a;
groupBOne = b1;
groupBTwo = b2;
groupCOne = c1;
groupCTwo = c2;
groupCThree = c3;
groupD = d;
groupE = e;
groupF = f;
}
}
【问题讨论】:
标签: c# list recursion combinations