尽可能短,我有:
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;
我希望缩短它:
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);
}
答案 0 :(得分:3)
你想要这个吗?
YLIST = XLIST.Select(x => new Y
{
a1 = x.p1,
a2 = x.p2,
a3 = x.p3.ToString(),
a4 = x.p4.Trim()
}).ToList();
它使用lambda(如你标记的那样)并且(非常)略短......
答案 1 :(得分:2)
假设可以访问字段:
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();