LINQ:如何使用LINQ展平深层嵌套对象

时间:2013-05-31 20:56:11

标签: c# linq

我正试图将该模型压缩成集合。

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;          

}

我需要使用LINQ将它们转换为以下类型的对象集合:

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

 }

我尝试过selectmany,但我不够深入。

1 个答案:

答案 0 :(得分:4)

你可以这样做:

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,
    };

或者如果您更喜欢流利的语法:

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,
                });