我正试图将该模型压缩成集合。
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,但我不够深入。
答案 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,
});