2017-02-24 49 views
0

我有類似下面的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": [] 
      } 
     ] 
     } 
    ] 
    } 
] 
+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); 
+0

這起作用。 2步驟允許檢查null。謝謝 –

+0

如果'topics.FirstOrDefault'返回'null',則會出錯。 –