KKS
KKS

Reputation: 3630

Using LINQ to XML how can I group element on the basis of its value?

Below is the structure of my xml file:

<adlibXML>
   <recordList>
        <record priref="1" selected="False">
              <collection>TEXTILES</collection>
              <someotherelements>xyz</someotherelements>
        </record>
        <record priref="2" selected="False">
                  <collection>CERAMICS</collection>
                  <someotherelements>xyz</someotherelements>
        </record>
        <record priref="3" selected="False">
                  <collection>PAINTING</collection>
                  <someotherelements>xyz</someotherelements>
        </record>
        <record priref="4" selected="False">
                  <collection>TEXTILES</collection>
                  <someotherelements>xyz</someotherelements>
        </record>
   </recordList>

I am fetching this xml file using some APIs from a database from a vendor. I have three tables in my new database, Catalogue, Collection and Artifacts. I want to group the collection element on the basis of its value like 'TEXTILES','CERAMICS' etc. and a counter variable to count the number of collections I have. Using which I can then create collectionID & collectionTitle dynamically in my Collection table.

I am not able to solve it. Till now I have only done this bit of code:

var getcontent = from record in xmldoc.Descendants("record")
                 //this group by doesn't work
                 group record by record.Element("collection")
                 select record.Element("collection").Value;                     

foreach (var node in getcontent)
{
    Response.Write("Collection: " + node + "<br/>");
}

Upvotes: 0

Views: 3244

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167436

Try along the following lines:

var groups = from record in xmldoc.Descendants("record")
             group record by (string)record.Element("collection") into g
             select new {
               key = g.Key,
               count = g.Count()
             }

foreach (var group in groups)
{
  Response.Write("Collection " + group.key + " has " + group.count + " member(s).");
}

Upvotes: 3

Related Questions