1

我正在尝试将该模型展平为收藏。

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 ;

 }

我已经尝试过 selectman,但我还不够深入。

4

1 回答 1

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,
                });
于 2013-05-31T21:00:11.210 回答