假设我有以下内容:
public class ClassA
{
public string Description {get;set;}
public List<Product> Products {get;set;}
}
public class ClassB
{
public string Description {get;set;}
public Product SingleProduct {get;set;}
}
public class ClassC
{
public List<ClassA> ListOfAs {get;set;}
public List<ClassB> BreakDownListOfAs()
{
// This is the critical point
}
}
在标记的关键点,我想返回从检查ClassB
创建的ListOfAs
个实例的列表并对其进行分解,以便ClassB
的每个实例都有一个产品和{来自Description
所在的ClassA
实例的{1}}。
示例,如果我有:
Product
然后var ListOfAs = new List<ClassA> {
new ClassA {
Description = "foo",
Products = new List<Product> { p1, p2 }
},
new ClassA {
Description = "bar",
Products = new List<Product> { p3, p4 }
}
};
的返回值应匹配:
ClassC.BreakDownListOfAs()
我知道我通常会使用new List<ClassB> {
new ClassB { Description = "foo", Product = p1 },
new ClassB { Description = "foo", Product = p2 },
new ClassB { Description = "bar", Product = p3 },
new ClassB { Description = "bar", Product = p4 },
}
来投射子列表,但我无法弄清楚如何使用父对象中的字符串来实现投影子元素的组合。
答案 0 :(得分:3)
使用LINQ语法非常简单:
var query = from a in listOfAs
from p in a.Products
select new ClassB
{
Description = a.Description,
SingleProduct = p
};
var result = query.ToList();
答案 1 :(得分:3)
在LINQ方法链中,它看起来像这样:
return ListOfAs
.SelectMany(a => a.Products,
(a, p) => new ClassB
{
Description = a.Description,
SingleProduct = p
})
.ToList();
诀窍是使用ClassA实例中的描述和ClassA列表中的Product来在结果选择器中创建对象。
答案 2 :(得分:1)
IEnumerable<ClassB> breakdown =
ListOfAs.Select(a => a.Products.Select(
p => new ClassB { Description = a.Description,
SingleProduct = p }))
.SelectMany(b => b);