我有类似于下面的主题的类定义与子项,它可以深入三级。我想要的是匹配项的直接父(作为列表/集合)。下面的代码将获得我想要的结果,但我必须使用2个步骤。我怎么能一步到位呢。
C#代码。
string id = 'edf23fb667f5';
var topics = GetTopics(); //Get the data from DB with childre
var topic = topics.FirstOrDefault(x => x.Children.Any(y => y.Id == id)); //First level match
var subTopic = topic?.Children.FirstOrDefault(y => y.Id == id); //Second level match
public class Topic
{
public string Id;
public string Name;
public List<Topic> Children;
}
我的样本json如下所示
[
{
"Id": "5174daff0f78",
"Name": "First Level",
"Children": [
{
"Id": "9ea17d89bc60",
"Name": "Second Level",
"Children": [
{
"Id": "afb2a0cd3bd9",
"Name": "Third Level 1",
"Children": []
},
{
"Id": "edf23fb667f5",
"Name": "Third Level 2",
"Children": []
},
{
"Id": "506b4cd4922b",
"Name": "Third Level 3",
"Children": []
}
]
}
]
}
]
答案 0 :(得分:0)
string id = "edf23fb667f5";
var topics = GetTopics();
var subTopic = topics.FirstOrDefault(x => x.Children.Any(y => y.Id == id))
.Children.FirstOrDefault(s => s.Id == id);