Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a list of object models onto another list using linq

Tags:

c#

linq

I have two object models that share some properties and a list of one type that I want to use to create a list of another type. For now, I have something like this (and it works):

List<ObjectA> TheListOfObjectsA = the result of some query;
List<ObjectB> TheListOfObjectsB = new List<ObjectB>();

foreach (ObjectA TheObjectA in TheListObjectsA)
{
   ObjectB TheObjectB = new ObjectB();

   TheObjectB.Prop1 = TheObjectA.Prop1;
   TheObjectB.Prop2 = TheObjectA.Prop2;

   TheListOfObjectsB.Add(TheObjectB);
}

I'm curious if and how I could rewrite this in a linq statement without the loop (even thought we know the linq statement will be executed as a loop).

like image 653
frenchie Avatar asked May 21 '14 12:05

frenchie


3 Answers

Do you mean this?

var TheListOfObjectsB  = TheListObjectsA.Select(a => new ObjectB() { Prop1  = a.Prop1, Prop2 = a.Prop2 }).ToList();
like image 119
Honza Kovář Avatar answered Nov 06 '22 05:11

Honza Kovář


List<ObjectB> TheListOfObjectsB = TheListOfObjectsA
    .Select(t => new ObjectB {
        Prop1 = t.Prop1,
        Prop2 = t.Prop2,
    }).ToList();

You have to call the ToList() method to get a List<ObjectB>. Otherwise, you will get an IEnumerable<ObjectB>;

like image 9
amiry jd Avatar answered Nov 06 '22 05:11

amiry jd


You could use ConvertAll:

var output = listA.ConvertAll(new Converter<ObjectA, ObjectB>(ObjectAConverter));

and then define the converter:

public static ObjectB ObjectAConverter(ObjectA a)
{
    var b = new ObjectB();

    b.Prop1 = a.Prop1;
    b.Prop2 = a.Prop2;

    return b;
}

Doing it this way, and defining the converter method in a public place, means you can do this conversion any time without having to duplicate the logic.

For more brevity you could even declare the converter statically somewhere:

private static Converter<ObjectA, ObjectB> _converter =
    new Converter<ObjectA, ObjectB>(ObjectAConverter);
public static Converter<ObjectA, ObjectB> ObjectAConverter { get { return _converter; } }

and then call it like this:

var output = listA.ConvertAll(TypeName.ObjectAConverter);
like image 3
Mike Perrenoud Avatar answered Nov 06 '22 05:11

Mike Perrenoud