Linq和C#中的克隆对象

Pau*_*ley 0 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

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

M.k*_*ary 7

变更ForEachSelect

List<MyObj> myObj2 = myObjs.Select(a => a.Clone()).ToList();
Run Code Online (Sandbox Code Playgroud)

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