rood
rood

Reputation: 12793

LINQ:How to flatten deep nested objects with LINQ

I'm trying to flatten that model into collection.

public class Category 
  {
      public string name;   
      public  string id;          
      public  Subcategory subcategory;
  }


public class Subcategory
{
   public string name;   
   public  string id;          
   public List<Product> products;
}


public class Product
{
   public string name;   
   public  string id;          
   public Supplier1 supplier1;
   public Supplier2 supplier2
}

public class Supplier1 
{
   public string name;   
   public  string id;          

}
public class Supplier2 
{
   public string name;   
   public  string id;          

}

I need to use LINQ to turn them into a collection of objects of the following type:

public class MixedClass 
 {
  public string  CategoryId;   
  public string  SubcategoryId;          
  public string  ProductId ;
  public string  Supplier1Id ;
  public string  Supplier2Id ;

 }

I've tried selectmany but I couldn't go deep enough.

Upvotes: 1

Views: 1542

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

You can simply do this:

var results = 
    from c in Categories
    from p in c.subcategory.products
    select new MixedClass()
    {
        CategoryId = c.id,
        SubcategoryId = c.subcategory.id,
        ProductId = p.id,
        Supplier1Id = p.supplier1.id,
        Supplier2Id = p.supplier2.id,
    };

Or if you prefer fluent syntax:

var results = Categories
    .SelectMany(c => c.subcategory.products, 
                (c, p) => new MixedClass()
                {
                    CategoryId = c.id,
                    SubcategoryId = c.subcategory.id,
                    ProductId = p.id,
                    Supplier1Id = p.supplier1.id,
                    Supplier2Id = p.supplier2.id,
                });

Upvotes: 4

Related Questions