1

私はこのようなxmlを持っています:

<LiftFactors>
  <Products>
     <Product>
       <ProductId>Limella</ProductId>
       <Tactics>
         <Tactic>
           <Typ>PriceRed</Typ>
           <TPRFrom>0</TPRFrom>
           <TprThru>10</TprThru>
           <Lift>14</Lift>
           <VF>2012-01-09</VF>
           <VT>2012-01-11</VT>
        </Tactic>
        <Tactic>
           <Typ>PriceRed</Typ>
           <TPRFrom>10 </TPRFrom>
           <TprThru>20</TprThru>
           <Lift>30</Lift>
           <VF>2012-01-07</VF>
           <VT>2012-20-08</VT>
        </Tactic>
        <Tactic>
            <Typ>Display</Typ>
            <Lift>14</Lift> 
            <VF>2012-01-04</VF>
            <VT>2012-01-06</VT>
        </Tactic>
      </Tactics>
    </Product>
    <Product>
        <ProductId>Empower Cola</ProductId>
        <Tactics>
           <Tactic>
               <Typ>Display</Typ>
               <Lift>20</Lift>
               <VF>2012-01-01</VF>
               <VT>2012-01-08</VT>
           </Tactic>
        </Tactics>
    </Product>
  </Products>
</LiftFactors>

次の linq ステートメントでは、ProductId でグループ化され、ValidFrom の日付で並べ替えられた Tactic データを取得しています。

var xml = XElement.Parse(theXML);
var d =  (from e in xml.Descendants(@"Product")
          group e by e.Element("ProductId").Value into Items
         select Items).ToDictionary 
         (x => x.Key, x => ((XElement)x.First()).Descendants("Tactic").ToList().OrderByDescending (y=> ((DateTime)y.Element("VF"))));

出力:

  Limella -> Tactic PriceRed 1
          -> Tactic PriceRed 2
          -> Tactic Display
  Empower Cola -> Tactic Display

「Product」ノードはオプションであり、Product ノードの外側に Tactic ノードを追加できると仮定します。

<LiftFactors>
  <Products>
     <Product>
       <ProductId>Limella</ProductId>
       <Tactics>
         <Tactic>
           <Typ>PriceRed</Typ>
           <TPRFrom>0</TPRFrom>
           <TprThru>10</TprThru>
           <Lift>14</Lift>
           <VF>2012-01-09</VF>
           <VT>2012-01-11</VT>
        </Tactic>
       </Tactics>
     </Product>
   </Products>
   <Tactics>
         <Tactic>
           <Typ>PriceRed</Typ>
           <TPRFrom>0</TPRFrom>
           <TprThru>10</TprThru>
           <Lift>14</Lift>
           <VF>2012-01-09</VF>
           <VT>2012-01-11</VT>
         </Tactic>
   </Tactics>
</LiftFactors>

今私が欲しいのはこの出力です:

Limella -> Tactic 1
        -> ...
<Null>  -> Tactic 2
        -> ....

したがって、キーが割り当てられていないグループにも戦術が表示されるはずです。これは 1 つの linq クエリだけで可能ですか?

4

2 に答える 2

1

これを試して:

var d = xml.Descendants("Tactics")
           .GroupBy(e=>e.Parent.Name.LocalName == "Product" ?
                       e.Parent.Element("ProductId").Value : "")
           .ToDictionary(x => x.Key, x => ((XElement)x.First())
                                     .Descendants("Tactic").ToList()
                                     .OrderByDescending (y=>(DateTime)y.Element("VF")));

:Tactics外部のグループのProductキーはempty stringです。(If-else を使用して) コードを少し変更して、 に変更できますnull

于 2013-10-15T16:08:14.903 に答える