我有類似下面的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": []
}
]
}
]
}
]
*我想要得到的是眼前的母公司*。但是你也*想要「副標題」? –