一种解决方法是使用LINQ来手动映射List
到另一个List
。以下是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static class MappingExtensions
{
public static List MapToList(this List sourceList)
{
return sourceList.Select(x => AutoMapper.Mapper.Map(x)).ToList();
}
}
public class Program
{
public static void Main(string[] args)
{
// 初始化AutoMapper映射配置
AutoMapper.Mapper.Initialize(cfg => {
cfg.CreateMap();
});
// 源List对象
List sourceList = new List
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 }
};
// 使用自定义扩展方法手动映射源List到目标List
List destinationList = sourceList.MapToList();
// 输出目标List
foreach (Person person in destinationList)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
在上面的示例代码中,我们首先初始化了AutoMapper的映射配置。然后,我们创建了一个名为MappingExtensions
的扩展方法类,它包含一个名为MapToList
的扩展方法,用于手动映射List
到另一个List
。在Main
方法中,我们通过调用MapToList()
方法手动将源List对象映射到目标List对象。最后,我们遍历目标List并输出每个Person对象的属性。