2012-12-12 35 views
0

我有LINQ查詢其返回結果如下格式在LINQ獲取孩子的價值實體

 -- Parent1 
----Childs 
------key - aa 
------value - new 
----Childs 
------key - bb 
------value - old 
-- Parent2 
----Childs 
------key - cc 
------value - test 
----Childs 
------key - dd 
------value - tesst

我想使用LINQ在一個線來獲取孩子的價值。目前我能得到的價值,但兩行的代碼,我不喜歡它

var firstPoint = SeriesList.Select(i => i.Childs.Where(j => j.key == "aa")) 
          .FirstOrDefault(); 
decimal index = firstPoint.Select(d => d.Value) 
          .FirstOrDefault(); 
+0

它們之間的空檢查,你冒着得到'NullReferenceException'的風險。如果你想在這種情況下拋出一個異常,可以用'First()'代替。 – Bobson

回答

2
decimal index = SeriesList.Select(i => i.Childs.Where(j => j.key == "aa")) 
    .FirstOrDefault() 
    .FirstOrDefault().Value; 
1
var firstPoint = SeriesList.Select(i => i.Childs.Where(j => j.key == "aa")).FirstOrDefault().Value; 
+0

我試過得到了下面的錯誤'System.Collections.Generic.IEnumerable '沒有包含'Value'的定義,也沒有接受'System.Collections.Generic.IEnumerable'的第一個參數的擴展方法'Value'' –

+0

那麼'var firstPoint = SeriesList.Select(i => i.Childs.Where(j => j.key ==「aa」))。FirstOrDefault()。Select(d => d.Value).FirstOrDefault() ;'? – sed

1
decimal index = SeriesList.SelectMany(p => p.Childs) 
          .FirstOrDefault(c => c.key == "aa").Value; 

但請記住,所提供密鑰的孩子應該在列表中存在,否則你會得到一個例外。我認爲最好先找到孩子,然後如果孩子存在,得到其數值:由於您使用`FirstOrDefault()',如果你*不*做兩行,做一個

Childs child = SeriesList.SelectMany(p => p.Childs) 
          .FirstOrDefault(c => c.key == "aa"); 
if (child != null) 
    index = child.Value; 
+0

這在功能上與OPs代碼不同。他獲得第一個父母,然後獲得第一個孩子滿足X條件,從每個父母中獲得所有孩子,然後第一個孩子滿足條件。這可能是他想要的,但也可能不是。 – Servy

+0

@Servy同意,有一種方法可以找出OP需要的:)實際上,數據結構對我來說並不明確 - 每個父項中是否有多個Childs元素,或者不存在 –

+0

他的示例爲每個父項列出兩個子項,所以是。 – Servy