2009-09-10 9 views
1

Étant donné le code XML ci-dessous, je dois regrouper par InputItem et additionner les coûts pour toutes les années. Ainsi, les résultats devraient être:Regroupement et sommation dans LINQ to XML

  1. Contrats de recherche, 7000
  2. contrats techniques, 5000
  3. Hospitality, 2000

Voici le XML:

<Inputs> 
    <Inputs_Table_Row> 
     <InputItem>Research Contracts</InputItem> 
     <TotalYear1>1000</TotalYear1> 
     <TotalYear2>2000</TotalYear2> 
    </Inputs_Table_Row> 
    <Inputs_Table_Row> 
     <InputItem>Research Contracts</InputItem> 
     <TotalYear1>2000</TotalYear1> 
     <TotalYear2>2000</TotalYear2> 
    </Inputs_Table_Row> 
    <Inputs_Table_Row> 
     <InputItem>Technical Contracts</InputItem> 
     <TotalYear1>1000</TotalYear1> 
     <TotalYear2>2000</TotalYear2> 
    </Inputs_Table_Row> 
    <Inputs_Table_Row> 
     <InputItem>Technical Contracts</InputItem> 
     <TotalYear1>1000</TotalYear1> 
     <TotalYear2>1000</TotalYear2> 
    </Inputs_Table_Row> 
    <Inputs_Table_Row> 
     <InputItem>Hospitality</InputItem> 
     <TotalYear1>1000</TotalYear1> 
     <TotalYear2>1000</TotalYear2> 
    </Inputs_Table_Row> 
</Inputs> 

Voici ma tentative simplement pour regrouper jusqu'à présent, mais je n'ai pas eu de succès:

XDocument doc = XDocument.Load(@"c:\temp\CrpTotalsSimple.xml"); 

var query = from c in doc.Descendants("Inputs_Table_Row") 
      group new 
      { 
       Item = (string)c.Element("InputItem") 
      } 
      by c.Element("InputItem") 
      into groupedData 

      select new 
      { 
       ItemName = groupedData.Key.Value 
      }; 

foreach (var item in query) 
    Console.WriteLine(String.Format("Item: {0}", item.ItemName)); 

Comment puis-je résoudre ce problème?

Répondre

1

On dirait que je manquais juste d'utiliser Value dans la clause group by. Voici ma solution de travail:

var query = from c in doc.Descendants("Inputs_Table_Row") 
group new 
{ 
    Item = c.Element("InputItem").Value, 
    ItemValue = (int)c.Element("TotalYear1") + (int)c.Element("TotalYear2") 
} 
by c.Element("InputItem").Value 
into groupedData 

select new 
{ 
     ItemName = groupedData.Key, 
     ItemTotal = groupedData.Sum(rec => rec.ItemValue) 
    }; 
+0

BTW, je suis l'aide de cet article: http://blog.blocks4.net/post/2007/08/Querying-XML-documents-with-LINQ-to-XML .aspx – Graeme

2

Vous avez besoin quelque chose comme ...

var query = from yearTotalEl in doc.Descendants() 
      where yearTotalEl.Name.LocalName.StartsWith("TotalYear") 
      group (decimal)yearTotalEl 
      by (string)yearTotalEl.Parent.Element("InputItem") into g 
      select new {ItemName = g.Key, Sum = g.Sum()}; 

J'utilise decimal parce que je suppose que vous avez affaire à une monnaie qui peut avoir une composante fractionnaire - int serait par ailleurs très bien.