In my previous blog, I have explained how to group data present in a XML file and transform the output into a new XML file. In this blog I will transform the data into a custom Object. I will be using the same XML file
Products that I used in my previous blog, here is the link for my previous blog:
Grouping Data in XML File using LINQ-XML.
Now, I want to group the products data by category and store the results into following custom type:
- public class Product
- {
- public int ProductId { get; set; }
- public string ProductName { get; set; }
- public decimal Price { get; set; }
- public string Color { get; set; }
- }
-
- public class ProductsByCategoty
- {
- public string Category { get; set; }
- public List<Product> ProductsUnderEachCategory { get; set; }
- }
As you can see, the class design is straight forward, since we are grouping the products by category. In the ProductsByCategory class we have a property Category and since each category may have multiple products, we have a second property that will be a List of Product classes.
Here is the LINQ query to do that.
1. Method Syntax:
- List<ProductsByCategoty> productsByCategotyMS = products.Root.Descendants("Product")
- .GroupBy(p => p.Element("Category").Value)
- .Select(p => new ProductsByCategoty
- {
- Category = p.Key,
- ProductsUnderEachCategory = (p.Select(x => new Product
- {
- ProductId = Convert.ToInt32(x.Element("ID").Value),
- ProductName = x.Element("Name").Value,
- Price = Convert.ToDecimal(x.Element("Price").Value),
- Color = x.Element("Color").Value
- })).ToList()
- }).ToList();
2. Query Syntax:
- List<ProductsByCategoty> productsByCategotyQS = (from p in products.Root.Descendants("Product")
- group p by p.Element("Category").Value into g
- select new ProductsByCategoty
- {
- Category = g.Key,
- ProductsUnderEachCategory = (from x in g
- select new Product
- {
- ProductId = Convert.ToInt32(x.Element("ID").Value),
- ProductName = x.Element("Name").Value,
- Price = Convert.ToDecimal(x.Element("Price").Value),
- Color = x.Element("Color").Value
- }).ToList()
- }).ToList();
Now, we can simply fetch the output using a nested foreach loop:
- foreach (var item in productsByCategotyQS)
- {
- Console.WriteLine("Category: {0}", item.Category);
- foreach (var pro in item.ProductsUnderEachCategory)
- {
- Console.WriteLine("ProductId: {0}, Name: {1}, Price: {2}, Color: {3}",
- pro.ProductId, pro.ProductName, pro.Price, pro.Color);
- }
- Console.WriteLine("-------------------------------------------------------");
- }
Please let me know in case of any issues. Happy Coding :)