C# 如何查找对象列表中的所有对象';孩子是递归的吗?
我有一个需要处理的对象。此对象的类型为C# 如何查找对象列表中的所有对象';孩子是递归的吗?,c#,json,recursion,C#,Json,Recursion,我有一个需要处理的对象。此对象的类型为SchemaValidationResults,其中包含一个列表list NestedResults,该列表可能包含也可能不包含进一步的SchemaValidationResults对象 为了更清楚地说明这一点,我在下面提供了一个JSON表示。在这个JSON表示中有一个父对象,它包含一个具有两个子对象的子对象。其中一个子对象具有另一个子对象 因此,我们: Parent Child Child Child
SchemaValidationResults
,其中包含一个列表list NestedResults
,该列表可能包含也可能不包含进一步的SchemaValidationResults
对象
为了更清楚地说明这一点,我在下面提供了一个JSON表示。在这个JSON表示中有一个父对象,它包含一个具有两个子对象的子对象。其中一个子对象具有另一个子对象
因此,我们:
Parent
Child
Child
Child
Child
我需要能够检索这个JSON表示中没有任何子对象的对象。所以在上面的结构中,我需要这两个孩子
Parent
Child
Child <-- Need
Child
Child <- Need
这种性质使我相信递归将能够帮助我创建一个没有更多子对象的所有子对象的列表
然而,我开始写一个方法,我很快意识到我不确定应该如何构造方法来实现我想要的结果。到目前为止,我有:
public List<SchemaValidationResults> GetChildLessError(SchemaValidationResults errors)
{
List<SchemaValidationResults> childLessErrors = new List<SchemaValidationResults>();
foreach(var result in errors.NestedResults)
{
if(result.NestedResults.Count == 0)
{
childLessErrors.Add(result);
}
else
{
foreach(var resultChild in result.NestedResults)
childLessErrors.AddRange(GetChildLessError(resultChild));
}
}
return childLessErrors;
}
你有一个循环太多了 以下是您的代码的修订版本:
public List<SchemaValidationResults> GetChildLessError(SchemaValidationResults errors)
{
List<SchemaValidationResults> childLessErrors = new List<SchemaValidationResults>();
if(errors.NestedResults.Any())
{
foreach(var resultChild in errors.NestedResults)
{
childLessErrors.AddRange(GetChildLessError(resultChild));
}
}
else
{
childLessErrors.Add(errors);
}
return childLessErrors;
}
public List GetChildLessError(SchemaValidationResults错误)
{
List ChildlesErrors=新列表();
if(errors.NestedResults.Any())
{
foreach(var resultChild in errors.NestedResults)
{
AddRange(getChildlesError(resultChild));
}
}
其他的
{
添加(错误);
}
返回儿童的错误;
}
您的一个循环太多
以下是您的代码的修订版本:
public List<SchemaValidationResults> GetChildLessError(SchemaValidationResults errors)
{
List<SchemaValidationResults> childLessErrors = new List<SchemaValidationResults>();
if(errors.NestedResults.Any())
{
foreach(var resultChild in errors.NestedResults)
{
childLessErrors.AddRange(GetChildLessError(resultChild));
}
}
else
{
childLessErrors.Add(errors);
}
return childLessErrors;
}
public List GetChildLessError(SchemaValidationResults错误)
{
List ChildlesErrors=新列表();
if(errors.NestedResults.Any())
{
foreach(var resultChild in errors.NestedResults)
{
AddRange(getChildlesError(resultChild));
}
}
其他的
{
添加(错误);
}
返回儿童的错误;
}
答案就在问题的标题中:如何在对象的子对象列表中找到所有对象?答案就在问题的标题中:如何在对象的子对象列表中找到所有对象?递归地。
public List<SchemaValidationResults> GetChildLessError(SchemaValidationResults errors)
{
List<SchemaValidationResults> childLessErrors = new List<SchemaValidationResults>();
if(errors.NestedResults.Any())
{
foreach(var resultChild in errors.NestedResults)
{
childLessErrors.AddRange(GetChildLessError(resultChild));
}
}
else
{
childLessErrors.Add(errors);
}
return childLessErrors;
}