2010-10-17 20 views
0

Le plus court possible, je:Recette: copier une collection à l'autre (membre remap)

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; 

et je veux raccourcir ce:

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); 
} 
+1

Pouvez-vous être plus précis sur ce vous voulez dire par "raccourcir cela"? Voulez-vous dire que vous voulez faire cette copie dans une ligne ala ICollection.CopyTo? – villecoder

+0

Quelque chose comme XLIST.Foreach (x => {YLIST.Add (new Y {....})}) –

Répondre

3

Voulez-vous cela?

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

Il utilise un lambda (comme vous avez marqué) et il est (très) légèrement plus court ...

+0

+1, vous étiez un peu plus rapide. :) –

+0

@Jeff, ha, ouais, par 6 secondes je pense. ;) –

2

En supposant que les champs sont accessibles:

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();