问题
let's say I have a dynamic collection, which consists set of key-values.
for example:
[
{
key: test1,
value: [
{
key:c1level1,
value: [
{
key:settings-key,
value: c1level2Val
},
{
key: types,
value: typesVal
}
]
}
]
},
{
key: test2,
value: [
{
key:c2level1,
value: [
{
key:settings-key,
value: c2level2Val
},
{
key: types,
value: typesVal
}
]
}
]
}
]
and I want to get all the objects which have a key named "settings-key" and "types" and save them together in a List for example.
How can I achieve this?
I tried this but not works for this solution. when it goes deep in one node, the other stays outside and is never iterated. for example, when iteration is started and let's say it's on "test1" it ignores "test2" node and works arround only for "test1" node. which is already a problem:
foreach (var item in yaml)
{
if (item.Key == "settings-key" || item.Key == "types")
{
Type typeOfYaml = yaml.GetType();
string placeholderName = String.Empty;
bool placeholderNameExist = typeOfYaml.GetProperties().Where(p => p.Name.Equals("settings-key")).Any();
if (placeholderNameExist)
{
placeholderName = yaml["settings-key"];
}
else
{
return null;
}
List<object> types = null;
bool typesExist = typeOfYaml.GetProperties().Where(p => p.Name.Equals("types")).Any();
if (typesExist)
types = yaml["types"];
var data = new KeyValue
{
RowKey = placeholderName,
Types = types != null ? types.Select(x=>x.ToString()).ToArray() : null
};
return data;
}
else
{
GetKeyValue(yaml[item.Key]);
}
}
来源:https://stackoverflow.com/questions/51535791/c-sharp-get-all-property-conditionally-from-dynamic-collection-which-looks-like