使用Automapper,可以将一个列表映射到一个对象。下面是一个简单的示例,说明如何使用Automapper在C#中将一个列表映射到一个对象:
定义一个Person类,其中具有FirstName、LastName和Age属性:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
定义一个PersonDto类,其中具有FirstName、LastName和Age属性:
public class PersonDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
定义一个Automapper配置类,将Person映射到PersonDto:
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap();
}
}
在应用程序中的Startup类中注册Automapper:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAutoMapper(typeof(Startup));
// ...
}
在代码中使用Automapper将Person列表映射到PersonDto对象:
List people = new List
{
new Person { FirstName = "John", LastName = "Doe", Age = 25 },
new Person { FirstName = "Jane", LastName = "Doe", Age = 30 }
};
var configuration = new MapperConfiguration(cfg => cfg.AddProfile());
var mapper = configuration.CreateMapper();
PersonDto personDto = mapper.Map(people);
Console.WriteLine(personDto.FirstName); // John
Console.WriteLine(personDto.LastName); // Doe
Console.WriteLine(personDto.Age); // 25
在这个例子中,我们首先定义了一个人类和一个人Dto类,然后在映射配置类中设置映射。在启动类中注册Automapper。最后,我们创建一个人列表,然后使用Automapper将它映射到PersonDto对象。