我有类似下面的Topic类的子类定义,它可以进入三级深度。我想要得到的是匹配项目的直接父项(作为列表/集合)。下面的代码会得到我想要的结果,但我必须使用2个步骤。我怎样才能一步到位。Linq/lambda获得匹配子记录的直接父对象(三级对象)
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": []
}
]
}
]
}
]
*我想要得到的是眼前的母公司*。但是你也*想要“副标题”? –