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

bub*_*ing -1 c# linq extension-methods list

最近我参与了一些涉及跨各种数据域翻译对象的程序.所以我有很多映射方法(有时作为扩展方法),用于将一种类型的对象转换为另一种域中的另一种相似类型.通常,我还需要一种方法将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());
    }
}
Run Code Online (Sandbox Code Playgroud)

dca*_*tro 6

// This doesn't compile, of course, but I hope
// it illustrates what I'm intending to do:
this.ListOfA = listOfB.Select(b => b.MapToA());
Run Code Online (Sandbox Code Playgroud)

它不会编译,因为listOfB.Select(b => b.MapToA())生成的实例IEnumerable<A>不可分配List<A>.

使用ToList它应该编译好

this.ListOfA = listOfB.Select(b => b.MapToA()).ToList();
Run Code Online (Sandbox Code Playgroud)

  • @ryanyuyu如果它是`public static A MapToA(B b)`而不是实例方法,那将会有效. (3认同)
  • 奖励信息:由于大多数 Mapping 方法是一个 `Func`(一个具有非空返回的输入),您可以在 `Select` 语句中使用 Mapping 方法本身而不是 lambda `func`。`listOfB.Select(MapToA).ToList()`。 (2认同)