Linq和C#中的克隆对象

时间:2016-12-15 17:38:11

标签: c# linq

这个问题不是关于克隆对象,而是关于正确使用Linq来使用扩展方法来克隆对象列表。如果只是为了说明而编码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
   {
        static void Main(string[] args)
        {
           List<MyObj> myObjs = DB.GetAllMyObjs(); //fictitious database calls returns a list of Objs


        //I now want to use my extension method clone to clone all the MyObjs in myObjs
        // this throws an error;
        List<MyObj> myObj2 = myObjs.ForEach(a => a.Clone()).ToList(); //ERROR = "."cannot be applied to type void


    }
}

public class MyObj 
{
    public int Id { get; set; }



}
public static class MyObjExtentions
{
    public static MyObj  Clone(this MyObj myObj)
    {
        var myObjClone = new MyObj();
        myObjClone.Id = myObj.Id;
        return myObjClone;
    }
}

}

我在Linq代码上收到错误。可以这样做,还是需要一个foreach循环。

1 个答案:

答案 0 :(得分:6)

ForEach更改为Select

List<MyObj> myObj2 = myObjs.Select(a => a.Clone()).ToList();

ForEach是列表实现的一部分。不是linq