views:

38

answers:

2

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);
}
+3  A: 

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...

Kirk Woll
+1, you were a little faster. :)
Jeff M
@Jeff, ha, yeah, by 6 seconds I think. ;)
Kirk Woll
+2  A: 

Assuming the fields are accessible:

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