【问题标题】:Recipe: copy one collection to another (member remap)配方:将一个集合复制到另一个集合(成员重映射)
【发布时间】:2010-10-17 00:19:10
【问题描述】:

尽可能短,我有:

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

【问题讨论】:

  • 你能更具体地说明“缩短这个”是什么意思吗?你的意思是你想用 ICollection.CopyTo 在一行中进行复制吗?
  • 类似 XLIST.Foreach( x => { YLIST.Add(new Y{....}) } )

标签: c# collections lambda recipe


【解决方案1】:

你想要这个吗?

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

它使用 lambda(如您标记的那样)并且它(非常)略短...

【讨论】:

  • @Jeff,哈,是的,我认为是 6 秒。 ;)
【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2012-06-27
    • 2016-12-21
    相关资源
    最近更新 更多