2016-12-15 59 views
0

這個問題不是關於克隆對象,而是關於正確使用Linq來使用擴展方法來克隆對象列表。代碼如果僅僅是爲了說明。Linq和克隆C中的對象#

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

你有沒有想過使用ICloneable而不是擴展方法? – maximdumont

+2

我相當肯定'ForEach'不是LINQ。 – Abion47

+3

正確。 'ForEach()'是List(T)的一個方法。請參閱https://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx。最大的區別是所有的LINQ擴展都返回一些東西,而且本質上是不變的。 'ForEach'可以用來操縱迭代的對象。 – Michael

回答

6

變化ForEachSelect

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

的ForEach是列表實現的一部分。不linq