gpt4 book ai didi

c# - 如何根据C#中的条件组合具有不同属性的两个列表

转载 作者:行者123 更新时间:2023-12-04 10:24:01 25 4
gpt4 key购买 nike

我有两个列表-计划和具有不同属性的部门..
样本数据:


{
"plans": [
{
"planCode": "A",
"planShortName": "Apple",
"planType": null,
"bisPlanCode": "878",

},
{
"planCode": "B",
"planShortName": "Ball",
"planType": null,
"bisPlanCode": "536",

}
],
"divisions": [
{
"planCode": "878",
"divisions": [
{ divisionCode: "2", divisionName: "test2" },
{ divisionCode: "1", divisionName: "test1" }]
},
{
"planCode": "536",
"divisions": [
{ divisionCode: "3", divisionName: "test3" },
{ divisionCode: "1", divisionName: "test1" }
]
}
]
}


如何在 C# 中的plans.bisPlanCode == Divisions.plansCode 的条件下将这两个列表-plans 和divsions 组合成一个列表planDivisions。
所以最终结果应该是这样的

"planDivisions": [
{
"planCode": "A",
"planShortName": "Apple",
"planType": null,
"bisPlanCode": "878",
"divisions": [ { divisionCode: "2", divisionName: "test2" },
{ divisionCode: "1", divisionName: "test1" }]

},
{
"planCode": "B",
"planShortName": "Ball",
"planType": null,
"bisPlanCode": "536",
"divisions": [
{ divisionCode: "3", divisionName: "test3" },
{ divisionCode: "1", divisionName: "test1"

}]

}
]


我试图做的事情:


List<Data> planDivisions = new List<Data>();

Divisions.ForEach(division =>
{
var plan = Plans.Find(p => p.PlanCode == division.PlanCode);
if (plan != null)
{
Data data = new Data();
data.DivisionData = division;
data.PlanData = plan;
planDivisions.Add(data);
}

});


有什么有效的方法吗?

最佳答案

您可以使用 LINQ 来连接这两个数据列表。更多相关信息 here .

class Plan {
public int PlanCode { get; set; }
public string PlanShortName { get; set; }
}

class Division {
public int DivisionCode { get; set; }
public string DivisionName { get; set; }
}

class DivisionAssignment {
public int PlanCode { get; set; }
public List<Division> Divisions { get; set; }
}

public static void JoinExample() {
// do your deserialization stuff here
List<Plan> plans = ...;
List<DivisionAssignment> assignments = ...;

// join the data
var query = from plan in plans
join assignment in assignments on plan.PlanCode equals assignment.PlanCode
select new { PlanCode = plan.PlanCode, Divisions = assignment.Divisions };

// reach the joined data
foreach (var planDivision in query) {
... = planDivision.PlanCode;
... = planDivision.Divisions;
...
}
}

关于c# - 如何根据C#中的条件组合具有不同属性的两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60709943/

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