Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从具有子集合的实体到DTO的扁平集合的项目_C#_Automapper - Fatal编程技术网

C# 从具有子集合的实体到DTO的扁平集合的项目

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

我有一个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
{
    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 
                                              });