C# 从具有子集合的实体到DTO的扁平集合的项目
我有一个Foo对象的集合,每个对象都有一个条的集合 我想要的是将我的Foo集合投影到FooDTO,这将是一个扁平版本,每个孩子一个。我该怎么做 e、 g:C# 从具有子集合的实体到DTO的扁平集合的项目,c#,automapper,C#,Automapper,我有一个Foo对象的集合,每个对象都有一个条的集合 我想要的是将我的Foo集合投影到FooDTO,这将是一个扁平版本,每个孩子一个。我该怎么做 e、 g: public class Foo { public int Id { get; set; } public List<Bar> Bar { get; set; } } public class Bar { public string Name; } public class FooDto { p
public class Foo
{
public int Id { get; set; }
public List<Bar> Bar { get; set; }
}
public class Bar
{
public string Name;
}
public class FooDto
{
public int Id { get; set; }
public string BarName { get; set; }
}
我怎么做?可以使用地图吗?您可以使用结果选择器来展平集合。像这样:
var collection = foos.SelectMany(
l => l.Bar,
(foo, bar) => new FooDto
{
Id = foo.Id,
BarName = bar.BarName
});
如果您想将收藏作为列表,您可以附加.ToList。谢谢,这与我最后做的非常接近。我本来希望和Automapper合作,但我认为这是不可能的。
[
new FooDto{ Id = 1, BarName = "foobar"},
new FooDto{ Id = 1, BarName = "barfoo" }
new FooDto{ Id = 2, BarName = "2foobar"},
new FooDto{ Id = 2, BarName = "2barfoo" }
]
var collection = foos.SelectMany(
l => l.Bar,
(foo, bar) => new FooDto
{
Id = foo.Id,
BarName = bar.BarName
});