如何使用 LINQ(或其他方式)将 List<T1> 映射到 List<T2>

How do I map List<T1> to List<T2> using LINQ (or otherwise)

最近我参与了一些涉及跨各种数据域转换对象的程序。所以我有很多映射方法(有时作为扩展方法)用于将一种类型的对象转换为不同域中的另一种相似类型。通常,我还需要一种将 List<> 转换为所述类型的 List<> 的方法。这总是涉及到有一个简单地创建目标类型的 List<> 的方法,运行一个 foreach 循环以添加源 List<> 的每个元素(但对每个元素使用映射方法)并返回新列表。感觉非常重复,好像语言中可能内置了一些东西来执行此操作(也许在 LINQ 中?)。我已经研究了几个涉及 List.ForEach() 的类似问题及其优缺点(反正不是我要找的)。我将在下面用一些示例代码进行说明。也许没有办法做我想做的事,如果那是答案,那就是答案,但我希望也许有。请注意,这显然只是示例代码,关于我的整体程序设计的评论不会真正添加任何内容,因为这是手头问题的一个非常小的虚拟版本。

class A
{
    public Guid Id { get; set; }
    public string Email { get; set; }
    public string MemberCode { get; set; }
}

class B
{
    public string Email { get; set; }
    public string MemberCode { get; set; }

    // My custom mapping method
    public A MapToA()
    {
        return new A()
        {
            Id = Guid.NewGuid(),
            Email = this.Email,
            MemberCode = this.MemberCode
        };
    }

    // For list mapping, I have this, but I'd prefer
    // to do something else that could utilize my custom mapper.
    // Perhaps a built in LINQ method?
    public static List<A> MapToListOfA(List<B> listOfB)
    {
        List<A> listOfA = new List<A>();

        foreach (var b in listOfB)
        {
            listOfA.Add(b.MapToA());
        }

        return listOfA;
    }
}

// Class C shows what I currently do that I'd like to get
// away from:
class C
{
    public List<A> ListOfA { get; set; }
    // other properties unrelated to the problem

    // This is how I might use the MapToListOfA method,
    // but I'd rather have something better.
    public C(List<B> listOfB)
    {
        this.ListOfA = B.MapToListOfA(listOfB);
    }
}

// I'd like something more like this:
class D
{
    public List<A> ListOfA { get; set; }
    // other properties unrelated to the problem

    public D(List<B> listOfB)
    {
        // This doesn't compile, of course, but I hope
        // it illustrates what I'm intending to do:
        this.ListOfA = listOfB.Select(b => b.MapToA());
    }
}
// This doesn't compile, of course, but I hope
// it illustrates what I'm intending to do:
this.ListOfA = listOfB.Select(b => b.MapToA());

它无法编译,因为 listOfB.Select(b => b.MapToA()) 生成了一个 IEnumerable<A> 的实例,它不能分配给 List<A>

使用 ToList 应该可以正常编译

this.ListOfA = listOfB.Select(b => b.MapToA()).ToList();