Search code examples
c#collectionslambdarecipe

Recipe: copy one collection to another (member remap)


As short as possible, I have:

class X
{
     int p1;
     int p2;
     int p3;
     string p4;
}
class Y
{
     int a1;
     int a2;
     string a3;
     string a4;
}
list<X> XLIST;
list<Y> YLIST;

and I want to shorten this:

foreach (X x in XLIST)
{
    Y y=new Y();
    //  arbitrary conversion
    y.a1=x.p1;
    y.a2=x.p2-x.p1;
    y.a3=x.p3.ToString();
    y.a4=x.p4.Trim();
    YLIST.Add(y);
}

Solution

  • Do you want this?

    YLIST = XLIST.Select(x => new Y 
    { 
        a1 = x.p1, 
        a2 = x.p2, 
        a3 = x.p3.ToString(), 
        a4 = x.p4.Trim() 
    }).ToList();
    

    It uses a lambda (as you tagged) and it is (very) marginally shorter...