2016-04-26 9 views
0

whereorderby句を持つ親要素を選択するLINQクエリがあります。この最初の結果だけが必要なので、.Take(1)を適用します。次に、それぞれが "where"節を持つ親から2つの別々の子ノードを選択する必要があります。LINQサブクエリ後.Take(1)

2つの別個のLINQクエリを使用してこれを正常に実行しましたが、サブクエリで1つのクエリを必要とするように感じました。私をぶつけている部分は親の.Take(1)です。エラーなしで呼び出します。

これは私が今持っているものですが、これを1つのクエリに組み合わせることは可能ですか?

var parent= 
    (from parentXML in myDal.GetMyXML().Elements("parentElements") 
    where DateTime.Parse((string)parentXML.Attribute("startDate")) <= currentDate 
    orderby DateTime.Parse((string)parentXML.Attribute("startDate")) descending 
    select parentXML).Take(1); 

と:

var children = 
    (from firstChild in parent.Elements("childElements") 
    where (string)firstChild.Attribute("type") == "first" 
    from secondChild in parent.Elements("childElements") 
    where (string)secondChild.Attribute("type") == "second" 
    select new { first = firstChild , second = secondChild }).ToList(); 
+0

あなたは何エラーが出るんし、サンプルXMLを投稿することができますか? – rojobo

答えて

1

だけで簡単に試み:

var children = 
    (from parentXML in myDal.GetMyXML().Elements("parentElements") 
where DateTime.Parse((string)parentXML.Attribute("startDate")) <= currentDate 
orderby DateTime.Parse((string)parentXML.Attribute("startDate")) descending 
select parentXML).Select(p=>new { 
    first=p.Elements("childElements").Where(f=>f.Attribute("type")=="first"), 
    second=p.Elements("childElements").Where(f=>f.Attribute("type")=="second")}) 
.Take(1); 

リライト:

var children = 
    myDal.GetMyXML() 
    .Elements("parentElements") 
    .Where(p=>DateTime.Parse((string)p.Attribute("startDate"))<=currentDate) 
    .OrderByDescending(p=>DateTime.Parse((string)p.Attribute("startDate"))) 
    .Select(p=>new { 
     first=p.Elements("childElements").Where(f=>f.Attribute("type")=="first"), 
     second=p.Elements("childElements").Where(f=>f.Attribute("type")=="second")}) 
    .Take(1); 
+0

これはクローズ(非常にきれい)だと思われますが、「XElementにはどこの定義が含まれておらず、拡張子がXElement型の最初の引数を受け入れません」というメッセージがp.Where()にあります。 – DasBeasto

+0

'.Elements'は間違った場所にあります。 –

+0

ありがとうございました! – DasBeasto