简体   繁体   中英

How do I map two lists to one list in Automapper?

I have the following setup:

public class ClassA
{
    public int Id { get; set; }
    public int JoinId { get; set; }
}

public class ClassB
{
    public string Name { get; set; }
    public int JoinId { get; set; }
}

public class ClassC
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int JoinId { get; set; }
}

I have a list of ClassA and a list of ClassB

I want a list of ClassC using Automapper. The result should be a Full Outer Join on JoinId .

How can I achieve this?

For simplicity I'll assume these are contained within another class:

class Original 
{
    List<ClassA> ClassAs { get; set; }
    List<ClassB> ClassBs { get; set; }
}

class Result
{
    List<ClassC> ClassCs { get; set; }
}

You can map the former to the latter using

Mapper.CreateMap<Original, Result>().ForMember(x => x.ClassCs, 
    x => x.MapFrom(x.ClassAs.Join(
                        y.ClassBs, 
                        xEntry => xEntry.JoinId, 
                        yEntry => yEntry.JoinId, 
                        (xEntry, yEntry) => new ClassC { 
                                              Id = xEntry.Id, 
                                              Name = yEntry.Name, 
                                              JoinId = xEntry.JoinId});

Why not just write the code for it?

var listOfA = new List<A>();
var listOfB = new List<A>();
... // Code for adding values
listOfA.ToC(listOfB);

public static class OuterJoinExtension
{
    public static List<C> ToC(this List<A> listOfA, List<B> listOfB)
    {
        var listOfC = new List<C>();
        listOfA.ForEach(a => listOfB.ForEach(b =>
        {
            if (b.JoinId == a.JoinId)
            {
                listOfC.Add(new C { Id = a.Id, JoinId = b.JoinId, Name = b.Name });
            }
        }));
        return listOfC;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM